var cur = 0;
var Utils = {
	cp:'/fsPro',
	jsessionid:'',
	bie:$.browser.msie != undefined && $.browser.msie == true,
	bie6:$.browser.msie != undefined && $.browser.msie == true && $.browser.version == '6.0',
	minWidth:650,
	fast:false,
	print:false,
	loading:null,
	confirm:{},
	helpurl:'',
	lang:'zh-tw',
	layout:{},
	extform:{},
	validator:{},
	autodata:{},
	griddata:{},
	multisdata:{},
	iframe:{},
	msg:{},
	fixedtable:{},
	tabs:{},
	hidetabs:{},
	getVtabid:function(dpid,index,tabsize){
		if(index == null)index = 0;
		if(tabsize <= 1) return index;
		var strHtabs = $P.hidetabs[dpid];
		if(strHtabs == undefined || strHtabs == '') return index;
		var tmpIndex = index;
		while((","+strHtabs+",").indexOf(",tab"+tmpIndex+",") >= 0){
			tmpIndex ++ ;
			if(tmpIndex >= tabsize){
				tmpIndex = 0;
			}else if(tmpIndex == index){
				return index;
			}
		}
		return tmpIndex;
	},
	getdptab:function(id){
		return $P.tabs[id];
	},
	dptab:function(dptab,dpid,tabsize){
		this.dpid = dpid;
		this.dp = dptab;
		this.tabsize = tabsize;
		this.hide = function(tabid){
			var index = 0;
			try{
				index = parseInt(tabid.replace('tab',''));
			}catch(e){
				index = 0;
			}
			$P.hidetabs[this.dpid] += ','+tabid;
			index = $P.getVtabid(this.dpid,index,this.tabsize);
			this.dp.tabs("select",index);
			$('li[id='+this.dpid+'_'+tabid+']').hide();
		};
		this.show=function(tabid){
			var index = 0;
			try{
				index = parseInt(tabid.replace('tab',''));
			}catch(e){
				index = 0;
			}
			
			if(isNaN(index)){
				var li = this.dp.find('a[href=#'+tabid+']').parent();
				index = li.parent().find('>li').index(li);
			}
			$P.hidetabs[this.dpid] = (','+$P.hidetabs[this.dpid]+',').replace((','+tabid+','),'');
			$('li[id='+this.dpid+'_'+tabid+']').show();
			this.dp.tabs("select",index);
		};
		this.add=function(id,label,content){
			this.tabsize++;
			this.dp.tabs('add','#'+id,label);
			$('div[id='+id+']').append(content);
		};
		this.setTemplate=function(tp){
			this.dp.tabs('option','tabTemplate',tp);
		};
		this.setCloseTemplate=function(){
			var _dpid = this.dpid;
			this.setTemplate('<li><a href="#{href}">#{label}</a> <span class="ui-icon ui-icon-close" style="cursor: pointer;float: left;" onclick="var li=$(this).parent();$P.closeTab(\''+_dpid+'\',li.parent().find(\'li\').index(li))">Remove Tab</span></li>');
		};
	},
	closeTab:function(id,index){
		var tab = $P.getdptab(id);
		tab.dp.tabs( "remove", index );
		tab.tabsize=tab.tabsize-1;
	},
	isExsitTab:function(tabid){
		return $('div[id='+tabid+']').length > 0;
	},
	menus:{},
	getmenu:function(id){
		var menu = $P.menus[id];
		menu.xtype = 'menu';
		return menu;
	},
	getcontextmenu:function(id){
		var menu = $P.menus[id];
		menu.xtype = 'contextmenu';
		return menu;
	},
	menu:function(menu){
		this.config = {}
		this.xtype = 'menu';
		this.data = {};
		this.mu = menu;
		this.event = null;
		allUIMenus.push(this.mu);
		this.getMenu = function(){
			return this.mu;
		};
		this.getCaller=function(){
			return this.mu.getCaller();
		};
		this.show = function(caller,event){
			this.event = event;
			if (event.stopPropagation) {// this code is for Mozilla and Opera
				event.stopPropagation();
			}else if (window.event) {// this code is for IE
				window.event.cancelBubble = true;
			}
			
			var bfrist = !this.mu.menuExists;
			this.mu.setCaller(caller);
			if(!bfrist){
				this.setPostion(caller,event);
			}
			
			var bvalid = true;
			if((typeof this.config['bshow']) == 'function'){
				bvalid = this.config['bshow'].call(this);
			}
			
			if (this.mu.menuOpen == false) {
				if(bvalid){
					this.mu.showMenu(); 
					if(bfrist){
						this.setPostion(caller,event);
					}
				}
			}else{
				this.mu.kill();
				if(bvalid){
					this.mu.showMenu();
				}
			}
		};
		this.setPostion = function(caller,event){
			var parentel = this.mu.getContainer().parent();
			var cheight = this.mu.getContainer().height();
			var cwidth = this.mu.getContainer().width();
			var wheight = $(window).height();
			var wwidth = $(window).width();
			
			var x = 0;
			var y = 0;
			var ctop = 0;
			if(this.xtype == 'contextmenu'){
				ctop = 0;
				x = event.clientX;
				y = event.clientY;
			}else{
				ctop = $(caller).height();
				var offset = $(caller).offset();
				x = offset.left;
				y = offset.top;
				offset = null;
			}
			
			this.mu.getContainer().css('top',ctop+'px');
			if(wheight-y<=cheight){
				this.mu.getContainer().height(cheight);
				y = y - cheight-ctop-5;
			}
			
			if(wwidth-x<=cwidth){
				x = x - cwidth+$(caller).width();;
			}else{
				this.mu.getContainer().css('left','0px');
			}
			
			parentel.css('left',x+'px');
			parentel.css('top',y+'px');
		};
		this.enab = function(benab,action){
			var el = null;
			if(action == undefined){
				el = this.mu.getContainer().find("a")
			}else if((typeof action) == 'string'){
				el = this.mu.getContainer().find("a[value="+action+"]")
			}
			
			if(!el) return false;
			
			if(benab){
				el.removeAttr('enab');
				el.removeClass('ax-btn-disabled');
			}else{
				el.attr("enab","false");
				el.addClass('ax-btn-disabled');
			}
			delete el;
		}
	},
	dialogs:{},
	getdialog:function(id){
		return $P.dialogs[id];
	},
	dialog:function(dialog){
		this.data = {};
		this.items = {};
		this.dg = dialog;
		this.getDialog = function(){
			return this.dg;
		};
		this.isOpen = function(){
			return this.getDialog().dialog('isOpen');
		},
		this.open = function(){
			this.getDialog().dialog('open');
		};
		this.close = function(){
			this.getDialog().dialog('close');
		};
		this.getRecord = function (){
			var record = {};
			for(var key in this.items){
				var item = this.items[key];
				record[item['name']] = $P.form.gv(item['name'],item['nodename'],this.dg);
			}
			return record;
		};
		this.setRecord = function(record){
			for(var key in record){
				if(this.items[key] != undefined){
					$P.form.sv(key,record[key],this.items[key]['nodename'],this.dg);
				}
			}
		};
		this.setPostion = function(pos){
			this.getDialog().dialog( "option", "position", pos );
		};
		this.getel = function(name,nodename){
			return $P.form.getel(name,nodename,this.dg);
		};
		this.gv = function(name,def){
			return $P.gv($P.form.gv(name,$(this.items[name]).gv('nodename'),this.dg),def);
		};
		this.sv = function(name,value){
			return $P.form.sv(name,value,$(this.items[name]).gv('nodename'),this.dg);
		};
	},
	doYarncont:function(el){
		var dg = $P.getdialog('yarncont_tp');
		dg.sv("yarncont_tp",el.value);
		dg.data['el']=el;
		if(dg.data['tp_el'] == undefined || dg.data['tp_el'] == null){
			dg.data['tp_el'] = dg.getel("yarncont_tp").get(0);
		}
		$(dg.data['tp_el']).select1();
		dg.open();//打開對話框 
	},
	outYarncont:function(){
		var dg = $P.getdialog('yarncont_tp');
		if(dg.data['tp_el'] == undefined || dg.data['tp_el'] == null){
			dg.data['tp_el'] = dg.getel("yarncont_tp").get(0);
		}
		var jo = $P.validYarncont(dg.data['tp_el'].value.trim(),'yarncont_tp');
		
		if(dg.data['el'] && jo.ret == 1){
			dg.data['el'].value = jo.text; 
			dg.close();//打開對話框 
		}else if(jo.ret == 0){
			alert(jo.msg);
		}else{
			dg.close();//打開對話框
		}
	},
	validYarncont:function(tempvalue,_name){
		if(tempvalue.trim() == ""){return {ret:1,msg:"",text:""};}
		var msg = "";
		var text = "";
		try{
			var re = new RegExp("[^a-zA-Z\-_\(\)\\.]{1,}", "gi"); 
			var reVal = new RegExp("[a-zA-Z\-_\(\)\\.]{1,}", "gi"); 
			
			var ay1 = tempvalue.split(reVal);//比例
			if(ay1.length > 0){
				if(ay1[0].trim() == ""){
					ay1.shift();
				}
				
				if(ay1[ay1.length-1].trim() == ""){
					ay1.pop();
				}
			}
			var ay2 = tempvalue.split(re);//成份
			if(ay2.length > 0){
				if(ay2[0].trim() == ""){
					ay2.shift();
				}
				
				if(ay2[ay2.length-1].trim() == ""){
					ay2.pop();
				}
			}
			
			var rate = 0;
			if(ay1.length != ay2.length){
				msg = "成份格式不正確!"; 
			}
			
			var rep = {};
			for(var i = 0;msg == ""&& i<ay1.length;i++){
				if(!$P.isnumber(ay1[i],0,'0',100)){
					msg = "比例必須為0-100的整數!"; 
					break;
				}
				
				if(rep[ay2[i].toUpperCase()] == true){
					msg = "成份["+ay2[i]+"]重複!"; 
					break;
				} 
				rate += (ay1[i]*1);
				text += ay1[i];
				rep[ay2[i].toUpperCase()] = true;
				
				if($P.autodata[_name][ay2[i].toUpperCase()] != true){
					msg = "無此成份["+ay2[i]+"]!"; 
					break;
				}
				text += ay2[i].toUpperCase();
			}
			
			if(msg == "" && rate != 100){
				msg = "比例必須為100!";
			}
			
		}catch(e){
			msg = "未知錯誤!";
		}
		re = null;
		reVal = null;
		rep = null;
		return {ret:msg=="" ? 1:0,msg:msg,text:text}
	},
	toolbar:{
		enab:function(id,benab){
			var el = null;
			if((typeof id) == 'string'){
				el = $('[id='+id+']');
			}else if((typeof id) == 'object'){
				el = $(id);
			}
			if(!el) return false;
			
			if(benab){
				el.removeAttr('enab');
				el.removeClass('ax-btn-disabled');
			}else{
				el.attr("enab","false");
				el.addClass('ax-btn-disabled');
			}
			delete el;
		}
    },
    grid:{
    	editors:{},
    	config:{},
    	status:1,
    	keydownconfig:{},
    	regKeydownEvent:function(_config){
    		var config = {
    			tid:'grid1'//table id
    		};
    		$.extend(config,_config);
    		$P.grid.keydownconfig[config.tid] = config;
    		
    		if($P.isne($P.grid.keydownconfig[config.tabid])){
	    		var tab = $('table[id='+config.tid+']');
	    		$P.grid.regTrKeydownEvent(tab.find('tbody tr'));
    		}
    		
    		delete config;
			delete _config;
    	},
    	regTrKeydownEvent:function(tr){
    		tr.find('input[type=text]').keydown($P.grid.keydown);
    		tr.find('textarea').keydown($P.grid.keydown);
    	},
    	keydown:function(event,_me){
    		var me ;
    		if(_me != undefined)
    			me = _me ;
    		else
    			me = this ;
    		var code = event.keyCode;
    		
    		//if(code == 9) return false;
    		if(code == 9) {code = 39};
    		if(code == 13){$(me).select1();$(me).toggleClass('editFiled');}
    		
    		if((code == 37 
    		|| code == 38 
    		|| code == 39 
    		|| code == 40 ) && $(me).gv('class').indexOf('editFiled') < 0){
    			$P.grid.jmupFun(me,code);
    			if($(me).gv('class').indexOf('Wdate') >= 0){
    				try{$dp.cal.close();}catch(e){}
    			}
    			return false;
    		}
    		
    	},
    	jmupFun:function(me,code){
    		//jump
    		var el = this.getnextitem(me,code);
    		if(el != null){
    			if($(el)[0].nodeName.toLowerCase() == 'td'){
    				$(me).removeClass('editFiled');
    				if($(me)[0].nodeName.toLowerCase() == 'input' && $(me).val().trim() != $(me).gv('oldvalue')){
	    				$(me).trigger('change');
	    			}
    				
    				$(me).data("endeditor",function(){
    					setTimeout(function(){$(el).click();},100);
    					
    				});
    				
    				$(me).blur();
    				//$(el).find('#field').click();
    			}else{
    				$(me).removeClass('editFiled');
	    			$(el).select1();
    			}
    		}
    	},
    	getnextitem:function(me,code){
    		var tab = $(me).parents('table.listing:first');
    		var td = $(me).parents('td:first');
    		
    		var rows = tab.find('> tbody  tr').length;
    		var cols = tab.find('> tbody > tr:first >td ').length;
    		
    		try{
	    		var row ;
	    		var col ;
				if(td.gv('edit') == 'true'){
					row = td.gv('rowindex',0);
					col = parseInt(td.gv('colindex',0));
					
					if(row == '' && row != 0 && row != '0'){
						row = $I(td);
						col = $I(td,$(tab.find('tbody tr')[row]).find('td'));
					}else{
						row = parseInt(row);
					}
				}else{
					row = $(me).gv('index','') != '' ? $(me).gv('index','') : $I(me);
					col = $I(td,$(tab.find('tbody tr')[row]).find('td'));
				}
				
				var index = 0;
				var el = $P.grid.getnextitembypostion(tab,rows,cols,col,row,code,index);
				delete tab
				delete td;
				return el;	
    		}catch(e){return null}
    	},
    	getnextitembypostion:function(tab,rows,cols,col,row,code,index){
    		if(code == 37) {
    			if(index >= cols) return null;
    			col = col -1;if(col < 0)col=cols-1;
    		}
    		if(code == 39) {
	    		if(index >= cols) return null;
    			col = col +1;if(col >= cols)col = 0;
    		}
    		
    		if(code == 38){ 
    			if(index >= rows) return null;
    			row = row -1 ;if(row <0)row=rows-1;
    		}
    		if(code == 40){
    			if(index >= rows) return null;
    			row = row +1 ;if(row >=rows)row=0;
    		}
			
    		var td = $(tab.find('tbody > tr')[row]).find('> td')[col];
    		
    		var el ;
    		if($(td).gv('edit') == 'true'){
    			el = td;
    		}else{
    			el = $P.grid.getsubitembytd(td);
    		}
    		
    		if(el == undefined || el == null){
    			index ++ ;
    			delete td;
    			el=$P.grid.getnextitembypostion(tab,rows,cols,col,row,code,index);
    		}
    		return el;
    	},
    	getsubitembytd:function(parent){
    		if(parent == null || parent == undefined) return null;
    		var el ;
    		$(parent).children().each(function(){
    			var nodeName = this.nodeName.toLowerCase();
    			
    			if(nodeName== 'input' || nodeName == 'select' || nodeName == 'textarea'){
    				if($(this).gv('skip') != 'true' && $(this).isactive()){
    					el = this ;
    					return;
    				}
    			}
    			
    			if($(this).children().length >0)
    				el = $P.grid.getsubitembytd(this);
    		});
    		return el;
    	},
    	addrow:function(_config){
    		var config = {
    			tid:'grid1',//table id
    			tr_select:'',//tr select character
    			tr_html:'',//tr static html
    			postion:'last',//first last
    			reset:null,
    			loop:1
    		};
    		$.extend(config,_config);
    		
    		var tbody = $('table[id='+config.tid+'] tbody');
    		for(var i = 0; i<config.loop;i++){
    			config['tbody']=tbody;
				var tr ;
				if(!$P.isne(config.tr_html)){
					tr = $(config.tr_html);
				}else if(!$P.isne(config.tr_select)){
					tr = $(config.tr_select).clone();
				}else{
					tr = tbody.find('tr:first').clone()
				}
				if(tr == undefined) return;
				
				if(!$P.isne($P.grid.keydownconfig[config.tid])){
					$P.grid.regTrKeydownEvent(tr);
				}
				
				if(config.reset == null)
					this.resettr(tr);
				else if((typeof config.reset) == 'function'){
					config.reset.call(config,tr);
				}
				
				if((typeof config.bedit) == 'function'){
					config.bedit.call(config,tr);
				}
				
				tr.show();
				if('last' == config.postion){
					tbody.append(tr);
				}else if('first' == config.postion){
					tbody.prepend(tr);
				}
				
				if((typeof config.aedit) == 'function'){
					config.aedit.call(config,tr);
				}
				
				delete tr;
			}
			
			config = null;
			_config = null;
			
    	},
    	deleterow:function(_config){
    		var config = {
    			tid:'grid1',//table id
    			tr_select:'',//tr select character
    			tr:null,
    			loop:1
    		};
    		$.extend(config,_config);
    		var tbody = $('table[id='+config.tid+'] tbody');
    		config['tbody'] = tbody;
    		for(var i = 0; i<config.loop;i++){
	    		var tr ;
				if(!$P.isne(config.tr_select)){
					tr = tbody.find(config.tr_select);
				}else if(config.tr != null){
					if((typeof config.tr) == 'function'){
						tr = $(config.tr.call(config));
					}else{
						tr = config.tr;
					}
				}else{
					tr = tbody.find('tr:last');
				}
				if(tr == undefined || tr == null) return;
				
				if((typeof config.bdelete) == 'function'){
					config.bdelete.call(config,tr);
				}
				
				tr.each(function(){
					$(this).remove();
				});
				
				if((typeof config.adelete) == 'function'){
					config.adelete.call(config,tr);
				}
    		}
    		tbody = null;
    	},
    	resettr:function(tr){
    		if(tr == undefined) return;
    		tr.find('input[type=hidden]').val('');
    		tr.find('input[type=text]').val('');
    		tr.find('input[type=radio]').removeAttr('checked');
    		tr.find('input[type=checkbox]').removeAttr('checked');
    		tr.find('select').val('');
    		tr.find('textarea').val('');
    	},
    	fixedtable:function(tid,cid){
    		var xIE4Up, xIE8Up, xWebKit = navigator.userAgent.indexOf('AppleWebKit') > 0, xGecko = !xWebKit && navigator.product == 'Gecko';
    		 // Public Methods

			this.init = function(a, b, c, d){
			    this.clean();
			    return _ctor(a, b, c, d);
			};
			
			this.paint = function(){
		    	_event();
			};
			
			this.clean = function(){
				_dtor();
			};
			
		  	var _i = this,
		    _ic, // is collapse
		    _ce, // container element
		    _ta, // table array
		    _iw, // container is window
		    _bl = 0, _bt = 0, // container border left and top
		    _yo, // y-offset
    		yOfs,
    		bcenter;
    		// Constructor Code
    		if(tid){ _ctor(tid,cid,yOfs);}
    		
    		
    		// Private Methods
    		function _ctor(tid,cid,yOfs){
    			 var i, h, t;
			    _ta = $('[id='+tid+']');
			    
			    if(cid != ''){
			    	_ce = $('#'+cid)[0];
			    }else{
			    	_ce = $('#center')[0];
			    	bcenter = true;
				}
				
			    if (!_ta || !_ta.length || !_ce) { return false; }
			     
			    if (!(_iw = xDef(_ce.location))) { _ce.scrollTop = 0; }
			    	_yo = yOfs;
			    	
			    _ta.each(function(){
					h = this.tHead;
				    if (h) {
				    	t = document.createElement('table');
				    	t = $('<table cellspacing="0" cellpadding="0" border="0" style="overflow:hidden;"></table>')[0];
				        t.style.position = (_iw && !$P.bie ? 'fixed' : 'absolute');
				        t.style.top = '200';
				        t.className =  this.className;
				        if (this.cellSpacing !== '') { t.cellSpacing = this.cellSpacing; }
				        t.appendChild(h.cloneNode(true));
				        t.id = this.xthfHdrTblId = tid + '-xthf' + i;
				        this.xthfResize = 3; // do resize while > 0
				       
				        if (_iw && xNum(_yo)) {
				          if (_yo === 0) { t.style.top = xPageY(this) + 'px'; }
				          else { t.style.top = _yo + 'px'; }
				        }
				        document.body.appendChild(t);
				      }
			    });
			    
			    _ic =  $(_ta[0]).css('border-collapse') == 'collapse';

			    if (!_iw && !xIE8Up && !window.opera) {
			      	_bl = xGetComputedStyle(_ce, 'border-left-width', true),
			      	_bt = xGetComputedStyle(_ce, 'border-top-width', true);
			    }
			    
			    _event({type:'resize'});
			    
			    
			    if(_iw){
			    	$(window).scroll(_event);
			    }else{
			    	$(_ce).scroll(_event);
			    }
			    xAddEventListener(window, 'resize', _event, false);
			    xAddEventListener(window, 'unload', _dtor, false);
			    return true;    
    		}
    		
			function _dtor(){
    			var i, ht;
			    if (_ce) {
			    	xRemoveEventListener(_ce, 'scroll', _event);
      				xRemoveEventListener(window, 'resize', _event);
     				xRemoveEventListener(window, 'unload', _dtor);
     				
      				// Remove the header tables from the DOM.
     				for (i = 0; i < _ta.length; ++i) {
        				ht = xGetElementById(_ta[i].xthfHdrTblId);
        				if (ht) { document.body.removeChild(ht); }
        				_ta[i] = null;
      				}
	      			_ta = null;
	      			_ce = null;
    			}
  			}
    		
    		function _event(e){
			    var i, r;
			    e = e || window.event;
			    _ta.each(function(){
			    	_paint(this, r);
			    });
			}
			
			function _paint(t, r){			
			    var i, bl = 0, br = 0, c1, c2, cl, ct, ht, pl, sl, st, ty, thy,oth,tabtoolbar;
			    if (!t) { return; }
			   	
			    ht = xGetElementById(t.xthfHdrTblId);
    			st = xScrollTop(_ce, _iw) + (_yo || 0);
    			st += $P.center_top;
    			
    			tabtoolbar = $('#tabletoolbar-'+tid);
    			
    			oth = $P.gv(tabtoolbar.height(),0);
    			if(!bcenter || oth == '' || true) oth = 0 ;
    			
			    if (_iw) { ty = xPageY(t); }else { ty = t.offsetTop; }
			    thy = ty + t.rows[0].offsetTop;
			    
			    if (!_iw && !window.opera) {
			      thy -= xGetComputedStyle(t, 'border-top-width', 1);
			    }
			    
			    // Hide or show
			    if (xScrollTop(_ce, _iw) <= ty ||  st <= thy || st > ty + t.offsetHeight - ht.offsetHeight) {
			      	t.xthfResize = 3; // do resize while > 0
			      	if (_yo !== 0) {
						ht.style.left = '-10000px'; // hide it
						if(bcenter && oth >0){
							tabtoolbar.css('position','relative');
							tabtoolbar.css('top',0);
							tabtoolbar.css('left',0);
							tabtoolbar.css('height',oth);
							tabtoolbar.css('background-image','url(about: blank)');
							tabtoolbar.css('background-attachment','fixed');
							
						}
			        	return;
			      	}
			    }
			    
			    //table toolbar
			   	if(bcenter && oth > 0){
			   		tabtoolbar[0].style.position = (!$P.bie ? 'fixed' : 'absolute');
			   		
			   		if($P.bie){
				    	tabtoolbar[0].style.left = (xScrollLeft(_ce)) + 'px';
				    	tabtoolbar[0].style.top = (xScrollTop(_ce, _iw) + _bt) + 'px'; 
				    }else{
				   		tabtoolbar[0].style.left = (xPageX(t)) + 'px';
				   		tabtoolbar[0].style.top = (xPageY(_ce) + _bt) + 'px'; 
				    }
			   	}
			    
			    // Position
			    if($P.bie && _iw){
			    	ht.style.left = (xPageX(t) + _bl) + 'px';
			    }else{
			   		ht.style.left = (xPageX(t) - xScrollLeft(_ce, _iw) + _bl) + 'px';
			    }
			    
			    if (!_iw) {
			    	if (_yo === 0) { ht.style.top = (xPageY(t) + _bt+oth) + 'px'; }
			      	else { ht.style.top = (xPageY(_ce) + _bt+oth) + 'px'; }
			    }else{
			    	if($P.bie){
			    		ht.style.top= (st-3+oth)+'px';
			    	}else{
			    		ht.style.top=($P.center_top-2+oth)+'px';
			    	}
			    }
			    
			    // Resize
				if (t.xthfResize || r) {
			    	if (window.opera) {
        				copyCssWidth(t, ht);
      				}else {
        				bl = xGetComputedStyle(t, 'border-left-width', 1);
        				br = xGetComputedStyle(t, 'border-right-width', 1);
				        if (xIE8Up || (xGecko && _ic) || $P.bie) {
				        	if($P.bie6){
         						bl = br = 1;
         					}else if($P.bie)
         						bl = br = 1;
         					else
         						bl = br = 0.5;
        				}else if (xWebKit && _ic) {
          					bl = Math.round((bl + br) / 2);
          					br = 0;
        				}
        				ht.style.width = (t.clientWidth + bl + br) + 'px';
					}
					
	     			c1 = xGetElementsByTagName('th', t.tHead);
	      			c2 = xGetElementsByTagName('th', ht.tHead);
	      			for (i = 0; i < c1.length; ++i) {
		        		if (xIE4Up) {
		          			c2[i].style.width = (c1[i].clientWidth - parseInt(c1[i].currentStyle.paddingLeft) - parseInt(c1[i].currentStyle.paddingRight)) + 'px';
		        		}
		        		else {
		          			copyCssWidth(c1[i], c2[i]);
		        		}
	      			}
	      			if (t.xthfResize > 0) --t.xthfResize;
				}
				
	   	 		// Clip
			    if (!_iw) {
			      sl = xScrollLeft(_ce);
			      pl = xGetComputedStyle(_ce, 'padding-left', 1);
			      cr = _ce.clientWidth + sl - pl;
			      cl = sl - pl;
			      ht.style.clip = 'rect(auto,' + cr + 'px,auto,' + (cl < 0 ? '0' : cl) + 'px)';
			    }
  				
			} 
			
			function copyCssWidth(s, d){
			  d.style.borderLeftWidth =  $(s).css('border-left-width');
			  d.style.paddingLeft = $(s).css('padding-left');
			  d.style.width = $(s).css('width');
			  d.style.paddingRight = $(s).css('padding-right');
			  d.style.borderRightWidth = $(s).css('border-right-width');
    		}
    	
    	}
    },
    form:{
    	enabitems:{},
    	vformid:[],
    	status:0,
    	formid:'form1',
    	formel:null,
    	getForm: function(){
    		if($P.form.formel != null && $P.form.formel != undefined) return $P.form.formel;
    		
    		if($P.form.formid == '')$P.form.formid = 'form1';
    		$P.form.formel = document.forms[$P.form.formid];
    		return $P.form.formel;
    	},
    	items:[],
    	appendRecords: function(records,gridid){
    		if(gridid == undefined)gridid='grid1';
    		if($P.form.formid == '')$P.form.formid = 'form1';
    		var form = $(document.forms[$P.form.formid]);
    		for(var i in records){
				var el = $("<input name='"+gridid+"_records' type='hidden' />");
				el.attr("value",$P.jsonToString(records[i],"\""));
				form.append(el);
				el = null;
			}
			form = null;
    	},
    	getel:function(name,_nodename,parentel){
    		if(_nodename == undefined) _nodename = '';
    		var el = null;
    		if(parentel != undefined){
    			el = $(_nodename+'[name='+name+']',parentel);
    		}else{
    			el = $(_nodename+'[name='+name+']');
    		}
    		if(el.length == 0){
    			if(parentel != undefined){
    				el = $('#'+name,parentel);
        		}else{
        			el = $('#'+name);
        		}
    		}
    		return el;
    	},
    	gv: function(name,_nodename,parentel){
    		if(_nodename == undefined) _nodename = '';
    		var el = null;
    		if(parentel != undefined){
    			el = $(_nodename+'[name='+name+']',parentel);
    		}else{
    			el = $(_nodename+'[name='+name+']');
    		}
    		if(el.length == 0){
    			if(parentel != undefined){
    				el = $('#'+name,parentel);
        		}else{
        			el = $('#'+name);
        		}
    			
    			if(el.length > 0){
    				delete el;
    				return el.text();
    			}
    		}
    		
    		if(el.length == 0){
    			delete el;
    			return '';
    		}
    		
    		var nodeName = el[0].nodeName;
    		if(nodeName == undefined){ 
    			delete nodeName;
    			return '';
    		}else{
    			nodeName = nodeName.toUpperCase();
    		}
    		
    		var type1 = $(el[0]).gv('type').toLowerCase();
    		var value = '';
    		if('checkbox' == type1 || 'radio' == type1){
    			value = $('[name='+name+']:checked').val(); 
    		}else{
    			if(el.length > 1){
    				value = [];
    				el.each(function(){
    					value.push($(this).val());
    				});
    			}else{
    				value = el.val();
    			}
    		}
    		
    		delete el;
    		delete type;
    		delete nodeName;
    		return value;
    	},
    	sv: function(name,value,_nodename,parentel){
    		if(_nodename == undefined) _nodename = '';
    		var el = null;
    		if(parentel != undefined){
    			el = $(_nodename+'[name='+name+']',parentel);
    		}else{
    			el = $(_nodename+'[name='+name+']');
    		}
    		if(el.length == 0){
    			if(parentel != undefined){
    				el = $('#'+name,parentel);
        		}else{
        			el = $('#'+name);
        		}
    			if(el.length > 0){
    				delete el;
    				el.text(value);
    			}
    		}
    		
    		if(el.length == 0){
    			delete el;
    			return ;
    		}
    		
    		var nodeName = el[0].nodeName;
    		if(nodeName == undefined){ 
    			delete nodeName;
    			return ;
    		}else{
    			nodeName = nodeName.toUpperCase();
    		}
    		
    		var type1 = $(el[0]).gv('type').toLowerCase();
    		if('checkbox' == type1 || 'radio' == type1){
    			if('checkbox' == type1){
    				$('[name='+name+']').attr('checked',false);
    				$('[name='+name+'][value='+value+']').attr('checked',true);
    			}else{
    				$('[name='+name+'][value='+value+']').attr('checked',true);
    			}
    		}else{
    			el.val(value);
    		}
    		
    		delete el;
    		delete type;
    		delete nodeName;
    	},
    	setRecord: function(record,params){
    		if(params == undefined){
				for(var key in record){
					$P.form.sv(key,$(record).gv(key,''));
				}
    		}else{
    			var ay = params.split(",");
    			for(var i = 0;i<ay.length;i++){
    				if(!$P.isne(ay[i])){
    					if(ay[i].split("|").length == 2){
    						$P.form.sv(ay[i].split("|")[0],$(record).gv(ay[i].split("|")[1],''));
    					}else{
    						$P.form.sv(ay[i],$(record).gv(ay[i],''));
    					}
    				}
    			}
    		}
		},
    	getRecord: function(params){
    		var record = {};
    		if(params == undefined){
	    		for(var i in $P.form.items){
					var name = $P.form.items[i];
					record[name] = $P.form.gv(name);
		    	}
    		}else{
    			var ay = params.split(",");
    			for(var i = 0;i<ay.length;i++){
    				if(!$P.isne(ay[i])){
    					if(ay[i].split("|").length == 2){
    						record[ay[i].split("|")[0]] = $P.form.gv(ay[i].split("|")[1]);
    					}else{
    						record[ay[i]] = $P.form.gv(ay[i]);
    					}
    				}
    			}
    		}
    		return record;
    	},
    	regKeydownEvent: function(ids){
	    	var ay ;
			if(ids != undefined){
				ay = ids.split(',');
			}else{
				ay = this.items;
			}
			
			for(var i in ay){
				var _name = ay[i];
				$('[name='+_name+']').each(function(){
					$(this).keydown($P.form.keydown);
				});
	    	}
	    	delete ay;
	    },
    	enterFun:function(me){
    		if($('#search-option').length == 0){
    			doAction({action:'search',actionvalue:''});
    		}else if($('#search-option ul li a[enab!=false]').length > 0){
    			var el = $('#search-option ul li a[enab!=false]')[0];
    			doAction({action:'search',actionvalue:$(el).gv('value')}); 
    		}
    	},
    	jmupFun:function(me){
    		var el = this.getnextitem(me);
    		if(el != null){$(el).focus1();}
    	},
    	loadingFun:function(me,tabid){
    		//loading
    		if($(me).gv('loading') == 'true'){
    				doLoading(tabid);
    		}
    		var el = this.getnextitem(me);
    		if(el != null){$(el).focus1();$(el).select1();}
    	},
    	keydownConfig:{},//code:enter,action:jump,search
    	keydown:function(event){
    		if(event.keyCode == 13){
    			if($P.form.keydownConfig['code'] == 13 || $P.form.keydownConfig['code'] == 'enter'){
    				if($P.form.keydownConfig['action'] == 'search'){
		    			$P.form.enterFun(this);
	    			}else if($P.form.keydownConfig['action'] == 'jump'){
	    				$P.form.jmupFun(this);
	    			}else if($P.form.keydownConfig['action'] == 'loading'){
	    				$P.form.loadingFun(this,$P.gv($P.form.keydownConfig['tabid'],'grid1'));
	    			}else if($P.form.keydownConfig['customaction'] != undefined){
	    				if((typeof $P.form.keydownConfig['customaction']) == 'function'){
							$P.form.keydownConfig['customaction'].call(this);
						}else{
	    					eval($P.form.keydownConfig['customaction']);
	    				}
	    			}
    			}
    		}
    	},
    	setfocus: function(bactive){
    		$($P.form.getfirstitem(bactive)).focus1();
    	},
    	setselect: function(bactive){
    		$($P.form.getfirstitem(bactive)).select1();
    	},
    	getfirstitem: function(bactive){
    		if($P.form.items.length == 0)return null;
    		var el = $('[name='+$P.form.items[0]+']')[0];
    		
    		if(bactive == true){
    			if(el != null && (!$(el).isactive() 
    			|| $(el).gv('type') == 'hidden'
    			|| $(el).gv('skip') == 'true')
    			){
					el = this.getnextitem(el);
				}
    		}
    		return el ;
    	},
    	getnextitem:function(me){
    		var el = null;
    		var name=$(me).gv('name');
    		var els = $('[name='+name+']');
    		if(els.length > 0 && $I(me) < els.length-1){
    			el = els[$I(me)+1];
    		}else{
    			for(var i in this.items){
    				if(name == this.items[i] && i<this.items.length-1){
    					el = $('[name='+this.items[parseInt(i)+1]+']')[0];
    					break;
    				}
    			}
    		}
    		if(el != null && (!$(el).isactive() 
    			|| $(el).gv('type') == 'hidden'
    			|| $(el).gv('skip') == 'true')
    			){
				el = this.getnextitem(el);
    		}
    		return el;
    	},
    	setcomboxtextvalue:function(id,key,value){
    		var el = $('#'+id);
    		if(!el) return;
    		var config = eval('({'+el.gv('config')+'})');
			for(var i in $P.autodata[key]){
				var row = $P.autodata[key][i];
				if(value == row['realvalue']){
					el.val(row['value']);
//					if((typeof config['onpicked']) == 'function'){
//						var record = {};
//						$.extend(record,row);
//						record['set']=true;
//						record['text']=record['value'];
//						record['value']=record['realvalue'];
//						record['realvalue']=null;
//						config['onpicked'].call(el[0],record);
//						delete record;
//					}
					delete row;
					break;		
				}
			}
			delete el;
    	},
    	comboboxblur:function(el){
    		if($P.gv($(el).val()).trim() == '' && $(el).gv('hiddenid') != ''){
    			$('#'+$(el).gv('hiddenid')).val('');
    			var config = eval('({'+$(el).gv('config')+'})');
    			if((typeof config['onpicked']) == 'function'){
					var record = {};
					record['text']='';
					record['value']='';
					config['onpicked'].call(el,record);
				}
    		}
    	},
    	reset:function(ids){
    		var ay ;
    		if(ids != undefined){
    			ay = ids.split(',');
    		}else{
    			ay = this.items;
    		}
    		
    		for(var i in ay){
    			var _name = ay[i];
    			var bEmpty = true;
    			$('[name='+_name+']').each(function(){
    				bEmpty = false;
    				var _nodeName = this.nodeName.toLowerCase();
    				
    				if('input' == _nodeName
    					&&( $(this).gv('type') == 'checkbox' ||  $(this).gv('type') =='radio')
    					){
    					$(this).removeAttr('checked');
    				}else if('span' == _nodeName){					
    						$(this).text('');
    				}else{
    					$(this).val('');
    				}
    				
    				if('combobox' == $(this).attr('xtype') && 'true' !=  $(this).attr('single')){
    					$('[name='+_name+'_text]').val('');
    				}	
    			});
    			
    			if(bEmpty){
    				$('[id='+_name+']').each(function(){
    					$(this).val('');
    					$(this).removeAttr('checked');
    					
						if('span' == this.nodeName.toLowerCase()){					
    						$(this).text('');
    					}
    				});
    			}
    		}
    		delete ay;
    	},
    	enabs:function(ids,benab){
    		var ay ;
    		var enab = true;
    		if((typeof ids) == 'boolean'){
    			enab = ids;
    			ay = this.items;
    		}else{
    			ay = ids.split(',');
    			enab = benab;
    		}
    		
    		for(var i in ay){
    			this.enab(ay[i],enab);
    		}
    		delete ay ;
    		delete enab ;
    	},
    	enab:function(id,benab){
    		//var els = $('[id='+id+']');
			//if(els.length == 0){
			//	els = $('[name='+id+']');
			//}
			
			var els = $('[id='+id+']');
			if(els.length == 0)
				els = $('[name='+id+']');
				
			els.each(function(){
				var el = $(this);
				var xtype = el.attr('xtype');
				var id = el.gv('id').trim();
				
				if(id != ''){
					if(!benab){
						$P.form.enabitems[id]=true;
					}else{
						$P.form.enabitems[id]=null;
					}
				}
				
				if('combobox' == xtype){
					$P.form.enabcombobox(el.attr('id'),benab,'true'==el.attr('single'));
					delete xtype;
		    		delete el;
		    		return;
				}
				
				var nodename = el[0].nodeName.toLowerCase();
				var type = el.attr('type');
				if('select' == nodename || 'radio' == type || 'checkbox' == type){
					$P.form.enabreadonly(el.attr('id'),benab);
					delete nodename;
		    		delete el;
		    		delete type;
		    		return;
				}
				
				$P.form.enabnoreadonly(el.attr('id'),benab);
			});
    	},
    	enabcombobox:function(id,benab,bsingle){
    		var el ;
    		if(bsingle)
				el = $('#'+id);
			else
				el = $('#'+id+'_text');
    		if(!benab){
	    		if($P.isie()){
	    			el[0].readOnly = true;
	    			el[0].disabled = true;
	    		}else{
		    		el.attr('readonly','true');	
		    		el.attr('disabled','true');	
		    	}
		    	
		    	el[0].readonly = 'readonly';
	    		el.attr('enab','false');
	    		el.addClass('ax-disabled');
    		}else{
    			if($P.isie()){
	    			el[0].readOnly = false;
	    			el[0].disabled = false;
	    		}
	    		else{
		    		el.removeAttr('readonly');
		    		el.removeAttr('disabled');
		    	}
    			
    			el.removeAttr('enab');
    			el.removeClass('ax-disabled');
    		}
    		delete el;
    	},
    	enabreadonly:function(id,benab){
    		var el = $('#'+id);
//    		el.readonly(benab);
    		if(!benab){
    			el.attr('enab','false');
    			el[0].disabled = true;
    			//el.addClass('ax-disabled');
    		}else{
    			el.removeAttr('enab');
    			el[0].disabled = false;
    			//el.removeClass('ax-disabled');
    		}
    		delete el;
    	},
    	enabnoreadonly:function(id,benab){
    		var el = $('#'+id);
    		if(!benab){
    			if($P.isie()){
	    			el[0].readOnly = true;
	    			el[0].disabled = true;
	    		}else{
		    		el.attr('readonly','true');	
		    		el.attr('disabled','true');	
	    		}
	    		
	    		el.attr('enab','false');
	    		
	    		el.addClass('ax-disabled');
    		}else{
    			if($P.isie()){
	    			el[0].readOnly = false;
	    			el[0].disabled = false;
	    		}
	    		else{
		    		el.removeAttr('readonly');
		    		el.removeAttr('disabled');
		    	}
    			
    			el.removeAttr('enab');
    			el.removeClass('ax-disabled');
    		}
    		delete el;
    	}
    },
	_defaultAction:'search',
	_layout:'normal',
	setLayout : function(layout){
		this._layout = layout;
	},
	setDefaultAction:function(action){
		this._defaultAction = action ;
	},
	getLang : function(){
		return this.lang;
	},
	setLang : function(lang){
		this.lang = lang;
	},
	isie : function(){
		return $.browser.msie == true;
	},
	isenab : function(arg){
		var el ;
		if(typeof arg == 'string')
			el = $('#'+arg);
		else 
			el = arg;
		return !(el.attr('enab') == 'false');
	},
	isNeedValidate:function(elment){
		var _actions = $(elment).attr('action');
		var action = $('input[name=action]').val();
		var _actionvalues = $(elment).attr('actionvalue');
		var actionvalue = $('input[name=actionvalue]').val();
		
		if(action == ''){
			action = $('input[name=actiontemp]').val();
			$('input[name=actiontemp]').val('');
		}
		
		if(action == ''){
			action = this._defaultAction;
		}
			
		if(actionvalue == '')
			actionvalue = $('input[name=actionvaluetemp]').val();
			$('input[name=actionvaluetemp]').val('');
		
		if(actionvalue == '')
			actionvalue = 'default';
		
		
		if(_actions == undefined || _actions == ''){
			if(this._defaultAction == action){
				if(_actionvalues == undefined || _actionvalues == ''){
					return true;
				}else{
					if(actionvalue == 'default' || (','+_actionvalues+',').indexOf(','+actionvalue+',') >= 0){
						return true;
					}else{
						return false;
					}
				}
			}
		}else if((_actions+',').indexOf(action+',') >= 0){
			if(_actionvalues == undefined || _actionvalues == ''){
					return true;
			}else{
				if(actionvalue == 'default' || (','+_actionvalues+',').indexOf(','+actionvalue+',') >= 0){
					return true;
				}else{
					return false;
				}
			}
		}	
		delete _actions;
		delete action;
		delete _actionvalues;
		delete actionvalue;
		return false ;
	},
	center_top:0,
	tabselect : function(ui,id,bcache){
		try{
			if($(ui.panel).gv('delay','') == 'true'){
				var ifrid = $(ui.panel).gv('ifrid','');
				if(ifrid != ''){
					var ifr = $('iframe[id='+ifrid+']');
					if(ifr.gv('rsrc') != ''){
						ifr.attr('src',ifr.gv('rsrc'));
						ifr.attr('rsrc','');
					}
				}
			}
		}catch(e){}
		
		$.cookie('tabindex_'+id,ui.index);
		setTimeout(function(){$P.refresh()},10);
	},
	checkboxChang:function(me){
		var name = $(me).gv('dname');
		var el = $(me).prev('input[name='+name+']');
		if(el.length == 0){
			el = $('input[name='+name+']').eq($I(me));
		}
		if($(me).attr('checked') == 'checked' || $(me).attr('checked') == 'true'){
			el.val($(me).val());
		}else{
			el.val('');
		}
		el == null;
	},
	northel:null,
	centerel:null,
	southel:null,
	northresizerel:null,
	refresh : function(){
		if($P.fast && 'normal' == this._layout) return;
		if('normal' == this._layout){
			var _width = $(window).width();
			if($P.northel == null )
				$P.northel = $('div[id=north]');
				
			$P.northel.width(_width);
			
			if(_width <=$P.minWidth){
				$P.northel.find('> div:first').width(_width <= $P.minWidth ? $P.minWidth : _width);
				$P.northel.css('overflow-x','scroll');
			}else{
				$P.northel.css('overflow-x','hidden');
				$P.northel.find('> div:first').width('');
			}
			
			if($P.northresizerel == null)
				$P.northresizerel = $('div[id=north-resizer]');
			if($P.northresizerel.find(':visible').length == 1){
				this.center_top = $P.northresizerel.height();
			}else{
				this.center_top = $P.northel.height();
			}
			
			if($P.centerel == null)
				$P.centerel = $('div[id=center]');
			//$('#center').css('margin-top',(this.center_top)+'px');
			$P.centerel.css('top',(this.center_top+2)+'px');
			$P.centerel.width(_width-8);
			
			
			if(_width <=$P.minWidth){
				$P.centerel.find('> div:first').width((_width-8) <= $P.minWidth ? $P.minWidth : (_width-8));
			}else{
				$P.centerel.find('> div:first').width('');
			}
			
			if($P.southel == null)
				$P.southel = $('div[id=south]');
			
			var center_height = $(window).height()-this.center_top-7-$P.southel.height();
			$P.centerel.height(center_height);
			
			//修復iframe 100%
			for(var key in $P.iframe){
				var ifr = $('iframe[id='+key+']');
				if(ifr.gv('height') == '100%')
					ifr.height(center_height-40);
			}
			
			$P.northel.width(_width);
			
			for(var key in $P.fixedtable){
				try{
					$P.fixedtable[key].paint();
				}catch(e){}
			}
			
			//if($P.isie()){
				//for(var key in $P.iframe){
					//$('#'+key)[0].width=($('#'+key).parent().parent()[0].clientWidth-25)+'px';
				//}
			//}
			
			for(var key in $P.extform){
				$P.extform[key].doLayout();
			}
		}else{
			//修復iframe 100%
			var center_height = 0;
			for(var key in $P.iframe){
				if(center_height==0){
					if($P.northel == null )
						$P.northel = $('div[id=north]');
					if($P.southel == null)
						$P.southel = $('div[id=south]');
					center_height = $(window).height()-$P.northel.height()-12-$P.southel.height();
				}
				
				var ifr = $('iframe[id='+key+']');
				if(ifr.gv('height') == '100%')
					ifr.height(center_height-40);
			}
			
			for(var key in $P.layout){
				$P.layout[key].resizeAll();
			}
		}
	},
	reseterror : function(errorid){
		errorid = errorid == undefined ? "errorMsg" : errorid;
		var erel = $("div[id="+errorid+"]");
		if(erel.html() != ''){
			$("input.errorFiled").removeClass("errorFiled");
			$("textarea.errorFiled").removeClass("errorFiled");
			$("select.errorFiled").removeClass("errorFiled");
			erel.hide();
			erel.html('');
			$P.refresh();
		}
	},
	getEmlment : function(id){
		if(id == undefined || id == '')
			return undefined;
		
		var items = $('#'+id);
		if(items && items.length > 0){
			return items[0];
		}else{
			if(document.getElementsByName(id).length > 0){
				return document.getElementsByName(id)[0];
			}
		}
	},
	onexportvalidate : function(actionvalue){
		if(actionvalue == 'xls' || actionvalue == ''){
			if($('#oldaction').val() == '' || $('#oldaction').val() == 'search'){
				var bvalid = false;
				if($('.listing tbody tr').length ==0){
					if(confirm($P.msg['epnodataerror'])){
						bvalid = true;
					}
				}else {bvalid = true;}
				
				if(bvalid && $('[name=pageing_page]').length > 0){
					if(!confirm('选择确定导出当前分页数据,选择取消导出符合当前条件的所有记录?')){
						$('input[name$=_page]').val('-1');
					}else{
						$('input[name$=_page]').val($('[name=pageing_page]').gv('realvalue','1'));
					}
				}
				return bvalid;
			}else{
				alert($P.msg['eperror']);
				$P.processresult({ret:1,okinfo:$P.msg['eperror']});
			}
		}
		
		return false;
	},
	processcheckitems:function(layout,data,config){
		var me ; 
		if((typeof layout) == 'string'){
			me = $('#'+layout)[0];
		}else{
			me = layout[0];
		}
		var id = config['id'];
		if(!(config && config.reset == false)){
			$(me).empty();
		}
		var chks = "";
		var checktpl = "<input type=\"checkbox\" value=\"{value}\" caption=\"{text}\" name=\"{name}\" id=\"{id}{index}\" index=\"{index}\"><span class=\"sx-buttoncaption\">{text}</span>";
		var index = 0;
		if(me && data){
			for(var i in data){
				var item = data[i];
				item['index']=index;
				item['id']=id;
				item['name']=id;
				chks +=$P.format(checktpl,item);
				index ++;
				item = null;
			}
		}
		$(me).append(chks);
		delete data;
	},
	processradioitems:function(layout,data,config){
		var me ; 
		if((typeof layout) == 'string'){
			me = $('#'+layout)[0];
		}else{
			me = layout[0];
		}
		var id = config['id'];
		if(!(config && config.reset == false)){
			$(me).empty();
		}
		var chks = "";
		var checktpl = "<input type=\"radio\" value=\"{value}\" caption=\"{text}\" name=\"{name}\" id=\"{id}{index}\" index=\"{index}\"><span class=\"sx-buttoncaption\">{text}</span>";
		var index = 0;
		if(me && data){
			for(var i in data){
				var item = data[i];
				item['index']=index;
				item['id']=id;
				item['name']=id;
				chks +=$P.format(checktpl,item);
				index ++;
				item = null;
			}
		}
		$(me).append(chks);
		delete data;
	},
	processoptions : function(obj,data,config){
		var me ; 
		if((typeof obj) == 'string'){
			me = $('#'+obj)[0];
		}else{
			me = obj[0];
		}
		
		if(!(config && config.reset == false)){
			$(me).empty();
		}
		
		var index = 0;
		if(!(config && config.emptysupport == false)){
			var op=new Option();
			op.value='';   
			op.text='--';	
			me.options[index]=op;
			index ++;
		}
		
		if(me && data){
			var boptionrender = config['optionrender'] != undefined && (typeof config['optionrender']) == 'function';
			for(var i in data){
				var op=new Option();
				$.extend(op,data[i]);					
				me.options[index]=op;
				if(boptionrender){
					config['optionrender'].call(me,me.options[index]);
				}
				index ++;
			}
			delete boptionrender;
		}
		delete data;
	},processautodata : function(id,data){
		var el = $('#'+id);
		if(el.length == 0)return;
		
		var name = el.gv('name');
		el.val('');
		$('#'+id+'_text').val('');
		
		$P.autodata[name]=null;
		$P.autodata[name]=data;
	},processmultisdata : function(id,data){
		var el = $('#'+id);
		if(el.length == 0)return;
		
		var name = el.gv('name');
		el.val('');
		
		var textid = el.gv('textid');
		if(textid != ''){
			$('#'+textid).val('');
		}
		
		$P.multisdata[name]=null;
		$P.multisdata[name]=data;
	},
	processresult : function(_JO,errorid) {
		var _bsucc = (_JO && _JO.ret != undefined);
		if(_bsucc ){
			if(!_JO['execjs'])$ARPB(_JO);
			$P.reseterror();
			
			try {
				var msgs = "<div style=\"padding-left:12px\">";
				var berror = false ;
				if(_JO.ret == 0){
					if(!$P.isnullorempty(_JO.info)){
						berror = true;
						msgs += "<a><img border=\"0\" align=\"top\" alt=\"locate the error\" src=\""+$P.cp+"/include/images/default/icon_alert_s.gif\"></a>";
						msgs += $.validator.format("<span {0}> 【{1}】 {2}</span><br>",
								_JO.ret == 1 ? 'style="color:black;"' : '', 
								'錯誤', 
								_JO.info) ;
					}
					if(_JO.errors != undefined){
						for (var i in _JO.errors){
							berror = true;
							var item = _JO.errors[i];
							var el = $P.getEmlment(item.formItemId);
							var caption = '錯誤';
							if( el != undefined){
								caption = $P.gv($(el).attr('caption'),'错误');
								$(el).addClass("errorFiled");
								
								msgs +=  "<a onclick=\"Utils.flashFormItemError('"+ $(el).attr('id')+ "')\" href=\"#\"><img border=\"0\" align=\"top\" alt=\"locate the error\" src=\""+$P.cp+"/include/images/default/icon_alert_s.gif\"></a>";
							}else{
								msgs += "<a><img border=\"0\" align=\"top\" alt=\"locate the error\" src=\""+$P.cp+"/include/images/default/icon_alert_s.gif\"></a>";
							}
							msgs += $.validator.format(" 【{0}】 {1} <br>", caption, item.errorInfo)
						}
					}
				}else if(_JO.ret == 1){
					if(!$P.isnullorempty(_JO.okinfo)){
						berror = true;
						msgs += "<a><img border=\"0\" align=\"top\" alt=\"locate the error\" src=\""+$P.cp+"/include/images/default/icon_ok.gif\"></a>";
						msgs += $.validator.format("<span {0}> 【{1}】 {2}</span><br>",
								_JO.ret == 1 ? 'style="color:black;"' : '', 
								'消息', 
								_JO.okinfo) ;
					}
				}else if(_JO.ret == 2){
					if(!$P.isnullorempty(_JO.warninginfo)){
						berror = true;
						msgs += "<a><img border=\"0\" align=\"top\" style=\"width:15px;height:15px;\" alt=\"locate the error\" src=\""+$P.cp+"/include/images/default/icon-warning.gif\"></a>";
						msgs += $.validator.format("<span {0}> 【{1}】 {2}</span><br>",
								_JO.ret == 2 ? 'style="color:black;"' : '', 
								'警告', 
								_JO.warninginfo) ;
					}
				}else if(_JO.ret == 3){
					if(!$P.isnullorempty(_JO.promptinfo)){
						berror = true;
						msgs += "<a><img border=\"0\" align=\"top\"  alt=\"locate the error\" src=\""+$P.cp+"/include/images/default/icon_info.gif\"></a>";
						msgs += $.validator.format("<span {0}> 【{1}】 {2}</span><br>",
								_JO.ret == 3 ? 'style="color:black;"' : '', 
								'提示', 
								_JO.promptinfo) ;
					}
				}
				
				msgs += "</div>";
				
				if(berror){
					errorid = errorid == undefined ? "errorMsg" : errorid;
					var element = $("div[id="+errorid+"]");
					element.html(msgs);
					element.fadeIn("slow");
					if(_JO.time != undefined &&( typeof _JO.time) == 'number'){
						setTimeout(function(){element.fadeOut("slow");element==null;},_JO.time * 1000);			
					}
				}
			} catch (e) {alert(e);}
			
			if(!_JO['execjs'])$ARP(_JO);
		}
	},
	multiselectok:function(dialogid){
		var dg = $P.getdialog(dialogid);
		var config = dg.data['multiConfig'];
		var bsingle = config['bsingle'];
		var me = config['me'];
		var ret = {};
		
		var value = '';
		var text = '';
		var bfirst = true;
		var split = $P.gv(config['split'],',');
		var valueAy = [];
		var textAy = [];
		
		if('table' == config['type']){
			$('[name=itemselect]:checked').each(function(){
				valueAy.push($(this).val());
				textAy.push($(this).attr('text'));
			});
			ret['value'] = valueAy;
			ret['text'] = textAy;
		}else{
			$('[name=itemselect]:checked').each(function(){
				if($P.gv($(this).val()) != ''){
					if(!bfirst){
						value += split;
						text += split;
					}else{
						bfirst = false;
					}
					value += $(this).val();
					text += $(this).attr('text');
				}
			});
			ret['value'] = value;
			ret['text'] = text;
		}
		
		if('table' == config['type']){
			ret['me']=me;
			ret['name']=config['datakey'];
			ret['columncnt']=config['columncnt'];
			$P.processmultiselect(ret);
		}else{
			if(bsingle){
				var oldvalue = me.val();
				me.val($P.gv(ret['value']));
				if(me.val() != oldvalue)me.trigger('change',{value:me.val(),oldvalue:oldvalue});
			}else{
				me.val($P.gv(ret['text']));
				hideel.val($P.gv(ret['value']));
				if(me.val() != oldvalue)me.trigger('change',{text:me.val(),value:hideel.val()});
			}
		}
		
		var _onpicked=config['onpicked'];
		if(_onpicked != null ){
			if((typeof eval(_onpicked)) == 'function'){
				eval(_onpicked).call(me,ret);
			}
		}
	},
	multiselect:function(config){
		var params = {};
		$.extend(params,config);
		var me = $(params['me']);
		var hideel = null;
		
		//處理ie $(this).prev()方法不兼容問題
		if(me.gv('name') == '' && me.parent().find('input').length > 0){
			me = me.parent().find('input:visible');
		}
		
		var bsingle = !(me.attr('single') == 'false');
		if(!bsingle){
			hideel = $('input[id='+me.attr('hiddenid')+']');
		}
		params['me'] = me;
		params['bsingle'] = bsingle;
		
		var url = params['url'];
		if($P.isne(url)){
			url = $P.cp+'/include/template/select.jsp';
		}
		if(url.indexOf('?') < 0){url+='?';}
		url+='&single='+$(params).gv('single','false');
		url+='&record='+$(params).gv('record','true');
		url+='&value='+$P.encode(me.val());
		
		params['data'] = $P.multisdata[params['datakey']];
		if('table' == params['type']){
			var value = '';
			params['name'] = params['datakey'];
			$('[name='+params['name']+']').each(function(){var tempvalue = $P.gv($(this).val());if(tempvalue != ''){value += (params['split']+$(this).val());}});
			params['value'] = value;
		}else{
			if(bsingle){
				params['value'] = me.val();
			}else{
				params['value'] = hideel.val();
			}
		}
		
		if(params['dialogid'] !=undefined){
			var dg = $P.getdialog(params['dialogid']);
			dg.data['multiConfig'] = params;
			var split = $P.gv(params['split'],',');
			var value = split+$P.gv(params['value'])+split;
			var chks = $('input[name=itemselect]',dg.dg);
			chks.each(function(){
				if((value).indexOf(split+this.value.trim()+split) >= 0)
					$(this).attr('checked',true);
				else
					$(this).attr('checked',false);
			});
			dg.open();//打開對話框 
			return ;
		}
		var ret = $P.showmodaldialog1(url,params,'',$(params).gv('windowwidth',400),$(params).gv('windowheight',400))
		if(ret){
			if(ret['action'] == 'clear'){
				me.val('');
				if(!bsingle)hideel.val('');
				var _onpicked=params['onpicked'];
				if(_onpicked != null ){
					if((typeof eval(_onpicked)) == 'function'){
						eval(_onpicked).call(me,ret);
					}
				}
				me.trigger('onpicked',ret);
			}else if(ret['action'] == 'set'){
				if('table' == params['type']){
					ret['me']=me;
					ret['name']=params['datakey'];
					ret['columncnt']=params['columncnt'];
					$P.processmultiselect(ret);
				}else{
					if(bsingle){
						var oldvalue = me.val();
						me.val($P.gv(ret['value']));
						if(me.val() != oldvalue)me.trigger('change',{value:me.val(),oldvalue:oldvalue});
					}else{
						me.val($P.gv(ret['text']));
						hideel.val($P.gv(ret['value']));
						if(me.val() != oldvalue)me.trigger('change',{text:me.val(),value:hideel.val()});
					}
				}
				
				var _onpicked=params['onpicked'];
				if(_onpicked != null ){
					if((typeof eval(_onpicked)) == 'function'){
						eval(_onpicked).call(me,ret);
					}
				}
				me.trigger('onpicked',ret);
			};
			me.focus1();
		}
		//delete me;
	},
	processmultiselect : function(ret){
		var me = ret['me'];
		var id = $(me).gv('id');
		var name = ret['name'];
		var valueAy = ret['value'];
		var textAy = ret['text'];
		var columncnt = $P.gv(ret['columncnt'],1);
		$(me).find('tbody').empty();
		
		if(valueAy != undefined && valueAy.length > 0){
			var tr ;
			for(var i=0;i<valueAy.length;i++){
				if(tr == undefined)tr=$("<tr></tr>");
				var td = $("<td></td>");
				td.append("<div class=\"jmx-tab-strip-close\" tableid=\""+id+"_table\" onclick=\"$P.deletemultiselectitem(this)\" style=\"padding-right:2px;margin-top:2px;margin-left:2px;\" >&nbsp;</div>");
				td.append($P.gv(textAy[i],'&nbsp;'));
				td.append("<input type=\"hidden\" name=\""+name+"\" value=\""+$P.gv(valueAy[i],'')+"\"/>");
				td.append("<input type=\"hidden\" name=\""+name+"_text\" value=\""+$P.gv(textAy[i],'')+"\"/>");
				tr.append(td);
				
				if((i+1)%columncnt == 0 || i== valueAy.length -1){
					if(i== valueAy.length -1 && (i+1)%columncnt >0){
						var subCnt = columncnt - (i+1)%columncnt;//补充td
						for(var k=0;k<subCnt;k++){
							tr.append("<td>&nbsp;</td>");
						}
					}
					$(me).find('tbody').append(tr);
					tr = null;
					tr=$("<tr></tr>");
				}
			}
			
		}else{
			$(me).find('tbody').append("<tr><td style=\"padding:0px;border:0px;\">&nbsp;</td></tr>");
		}
		$P.refresh();
	},
	deletemultiselectitem : function(me){
		var tableid = $(me).gv('tableid');
		var parent = $(me).parent();
		parent.empty();
		
		if(parent.parent().find('td div').length == 0){
			parent.parent().hide();
		}
		
		if($('#'+tableid+' tbody tr td:visible').length == 0){
			$('#'+tableid+' tbody').append("<tr><td style=\"border:0px;\">&nbsp;</td></tr>");
		}
		$P.refresh();
	},
	isnullorempty : function(arg){
		if((typeof arg)=='number' && !isNaN(arg))return false;
		if((typeof arg)=='boolean')return false;
		return arg == undefined || arg == '' || arg == null ;
	},
	isne : function(arg){
		return this.isnullorempty(arg);
	},
	gv: function(arg,def){
		if(this.isnullorempty(arg))
			return def || def == 0 ? def : '';
		else{
			if((typeof arg) == 'string')
				return arg.trim();
			else
				return arg;
		}
	},
	showerror2 : function(errorMap, errorList,errorid) {
		try {
			var msgs = "<div style=\"padding-left:12px\">";
			if(errorList && errorList.length > 0)$P.reseterror();
			for ( var i in errorList) {
				var msg = errorList[i].message;
				var el = errorList[i].element;
				var caption = $(el).attr('caption');
				if (caption == undefined || caption == '') {
					caption = $(el).attr('name');
				}
				$(el).addClass("errorFiled");
				msgs += "<a onclick=\"Utils.flashFormItemError('"
						+ $(el).attr('id')
						+ "')\" href=\"#\"><img border=\"0\" align=\"top\" alt=\"locate the error\" src=\""+$P.cp+"/include/images/default/icon_alert_s.gif\"></a>";

				msgs += $.validator.format(" 【{0}】 {1} <br>", caption, msg);
				delete msg;
				delete el;
				delete caption;
			}
			
			msgs += "</div>";
			
			if(errorList.length > 0){
				errorid = errorid == undefined ? "errorMsg" : errorid;
				var element = $("div[id="+errorid+"]");
				element.html(msgs);
				element.fadeIn("slow");
				if($P.loading != null)
					$P.loading.hide();
			}
			
			$P.refresh();
		} catch (e) {}
	},
	flashError:function(errorid){
		try{
			errorid = errorid == undefined ? "errorMsg" : errorid;
			var element = $("div[id="+errorid+"]");
			if (element != null) {
				
				element.fadeOut("fast");
				element.fadeIn("slow");
				
				delete element;
			}
		} catch (e) {alert(e)}
	},
	flashFormItemError : function(errorid) {
		try{
			var tabpageid = '';
	        var item = $("#"+errorid)[0];
	        if (item == null || item == undefined)
	            return;
	        var nCount = 50;
	        while (nCount > 0 && item != null && item != undefined) {
	            nCount--;
	            var _tabid = $(item).attr('id');
	            if(_tabid != undefined && _tabid.indexOf('tabs') == 0){
	            	tabpageid = _tabid;
	            	break;
	            }
	            item = item.parentNode;
	        }
	        
	        if (tabpageid != '') {
	           item = $("a[href=#"+tabpageid+"]");
	           if(item != undefined && item != null){
	        	   item.click();
	        	   $P.refresh();
	           }
	        }
	        delete item ;
	        
			var element = $("#" + errorid);
			if (element != null) {
				
				element.fadeOut("fast");
				element.fadeIn("slow");
				
				delete element;
			}
		} catch (e) {alert(e)}
	},
	download : function(url) {
		window.open(
						url,
						'',
						'resizable=1,menubar=0,status=0,titlebar=0,toolbar=0,scrollbars=0,width=30,height=30',
						false);
	},
	openwin : function(_URL, _TARGET, _STYLE, _REPLACE, _WIDTH, _HEIGHT) {
		var SCRW = screen.width;
		var SCRH = screen.height;
		
		if (_WIDTH == undefined || _WIDTH <= 0){
			_WIDTH = SCRW - (_WIDTH == -1 ? 0 : 80);
		}
		
		if (_HEIGHT == undefined || _HEIGHT <= 0){
			_HEIGHT = SCRH - (_HEIGHT == -1 ? 0 : 100);
		}
		
		var WLEFT = 0;
		var WTOP = 0;
		if (SCRW - _WIDTH > 0)
			WLEFT = (SCRW - _WIDTH) / 2
		if (SCRH - _HEIGHT - 30 > 0)
			WTOP = (SCRH - _HEIGHT - 30) / 2
		WTOP -= 10;
		if (WTOP < 0)
			WTOP = 5;

		if (_TARGET == '' || _TARGET == null)
			_TARGET = '';
		if (_STYLE == '' || _STYLE == null)
			_STYLE = 'resizable=1,menubar=0,status=0,titlebar=0,toolbar=0,scrollbars=1';
		var winWindow = window.open(_URL, _TARGET, _STYLE + ',width=' + _WIDTH
				+ ',height=' + _HEIGHT + ',left=' + WLEFT + ',top=' + WTOP,
				_REPLACE);
		return winWindow;
	},
	showmodaldialog : function(_URL, _PARAMS, _STYLE, _WIDTH, _HEIGHT) {
		var SCRW = screen.width;
		var SCRH = screen.height;
		
		if (_WIDTH <= 0)
			_WIDTH = SCRW - 80;
		if (_HEIGHT <= 0)
			_HEIGHT = SCRH - 100;

		var WLEFT = 0;
		var WTOP = 0;
		if (SCRW - _WIDTH > 0)
			WLEFT = (SCRW - _WIDTH) / 2
		if (SCRH - _HEIGHT - 30 > 0)
			WTOP = (SCRH - _HEIGHT - 30) / 2
		WTOP -= 10;
		if (WTOP < 0)
			WTOP = 5;

		if (_STYLE == '' || _STYLE == null)
			_STYLE = 'scroll: yes;status: no;resizable: yes;';
		_STYLE = _STYLE.replace(/=/g, ':');
		_STYLE = _STYLE.replace(/,/g, ';');
		var _RET = window.showModalDialog(_URL, _PARAMS, _STYLE
				+ ';dialogHeight: ' + _HEIGHT + 'px;dialogWidth: ' + _WIDTH
				+ 'px;' + 'dialogLeft:' + WLEFT + 'px;dialogTop:' + WTOP
				+ 'px;');
		return _RET;
	},
	showmodaldialog1 : function(_URL, _PARAMS, _STYLE, _WIDTH, _HEIGHT) {
		var SCRW = screen.width;
		var SCRH = screen.height;
		
		if (_WIDTH <= 0)
			_WIDTH = SCRW - 80;
		if (_HEIGHT <= 0)
			_HEIGHT = SCRH - 100;

		var WLEFT = 0;
		var WTOP = 0;
		if (SCRW - _WIDTH > 0)
			WLEFT = (SCRW - _WIDTH) / 2
		if (SCRH - _HEIGHT - 30 > 0)
			WTOP = (SCRH - _HEIGHT - 30) / 2
		WTOP -= 10;
		if (WTOP < 0)
			WTOP = 5;

		if (_STYLE == '' || _STYLE == null)
			_STYLE = 'scroll: yes;status: no;resizable: yes;';
		_STYLE = _STYLE.replace(/=/g, ':');
		_STYLE = _STYLE.replace(/,/g, ';');
		if(_PARAMS == undefined)_PARAMS={};
		_PARAMS['url'] = _URL;
		
		var _RET = window.showModalDialog($P.cp+'/include/template/frame.jsp?_random=time_'+new Date().getTime(), _PARAMS, _STYLE
				+ ';dialogHeight: ' + _HEIGHT + 'px;dialogWidth: ' + _WIDTH
				+ 'px;' + 'dialogLeft:' + WLEFT + 'px;dialogTop:' + WTOP
				+ 'px;');
		return _RET;
	},showOrg : function(_ME,_PARAMS,_onpicked){
		if($(_ME).gv('enab') == 'false') return false;
		var _name = $(_ME).attr("hdname");
		var el = $('input[name='+_name+']')[$I(_ME)];
		_PARAMS['value']=el.value;
		
		var _URL = $P.cp+"/include/common/orgiframe.jsp";
		$(_ME).data('isopen',true);
		var _RET = this.showmodaldialog(_URL, _PARAMS, '',500,500);
		$(_ME).data('isopen',false);
		if(_RET && _RET != undefined && _RET.ret == 'ok'){
			
			if(_RET.action == 'clear'){
				$(_ME).val('');
				el.value='';
			}else{
				$(_ME).val(_RET.text);
				el.value=_RET.value;
			}
			
			if((typeof _onpicked) == 'function'){
				_onpicked.call(_ME,_RET);
			}
			$(_ME).trigger('picked',_RET);
			$(el).trigger('picked',_RET);
			delete el;
		}
		return _RET;
	},ajax : function(_option){
		var op = {
			url:!$P.isnullorempty(_option.url) ? _option.url : $('#backpage').val(),
			type:'post',
			async:false,
			cache : false,  
			datatype:'text',
			success:function(response){
				var _JO = $P.parseresponse($.trim(response));
				var _bsucc = (_JO && _JO.ret != undefined);
				if(_bsucc){$ARPB(_JO);_JO['execjs'] = true;}
				if((typeof _option.succ) == 'function'){
					_option.succ.call(this,_JO);						
					delete _option;
				}
				
				if(_bsucc){
					$ARP(_JO);
					if(!_option.isValidate && _JO.ret != 1){$P.processresult(_JO);$P.refresh();}
				}
				_JO=null;
			}
		};
		$.extend(op,_option);
		$.ajax(op);
	},parseresponse: function(_RO) {
        var A = _RO;
        if (A != undefined && A != null && A != '') {
            var _JO = eval("(" + A + ")");
            return _JO;
        }
        return null;
    },cmp: function(option){
    	option['action']='ajax_CommonCmp';
    	var me = option.me; delete option.me;
    	var doaction = option.doaction;
    	if(doaction == null || doaction == undefined ){
    		doaction = function(jo){
    			if(!me) return;
    			if(jo != undefined && jo.ret == 1){
					if($(me).gv('ajaxsucc') != ''){
						eval($(me).gv('ajaxsucc'));
					}
				}else{
					if($(me).gv('ajaxfail') != ''){
						eval($(me).gv('ajaxfail'));
					}	
				}
    		}
    	}
    	delete option.doaction;
    	$P.ajax({data : option,succ :doaction,async:option['async'] == undefined ? true : option['async'],url:$P.cp+'/include/commonajax_backend.jsp'});
    },toggle : function(postion){
    	if('north' == postion){
    		var north = $('#north');
    		var resizer = $('#north-resizer');
    		
    		if(resizer.width() == 0){
    			resizer.width($('body').width());
    		}
    		
    		north.toggle();
    		resizer.toggle();
    	}
    	
    	this.refresh();
    	return false;
    },
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },
    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
 
            var c = string.charCodeAt(n);
 
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
 
        return utftext;
    },
 
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
 
        while ( i < utftext.length ) {
 
            c = utftext.charCodeAt(i);
 
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    },
    number:function(json){
    	return $P.isnumber(json['value'],json['dot'],json['min'],json['max']);
    },
    //validate 
	isnumber:function(value,dot,min,max){
		var ret = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		if(ret && (typeof dot) == 'number' && dot >=0){
			if(dot == 0){
				ret = /^-?\d+$/.test(value);		
			}else{
				eval("var rg = /^-?\\d+(\\.\\d{1,"+dot+"})?$/;");  
				ret = rg.test(value);
			}
		}
		
		var bminself = true;
		var bmaxself = true;
		if(ret && (typeof min) == 'string'){
			min = parseFloat(min);
			bminself = false;
		}
		if(ret && (typeof max) == 'string'){
			max = parseFloat(max);
			bmaxself = false;
		}
		
		if(ret && (typeof min) == 'number'){
			if(bminself)
				ret = parseFloat(value) >= min;
			else
				ret = parseFloat(value) > min;
		}
		
		if(ret && (typeof max) == 'number'){
			if(bmaxself)
				ret = parseFloat(value) <= max;
			else
				ret = parseFloat(value) < max;
		}
		return ret			
	},
	checkable: function( element ) {
		return /radio|checkbox/i.test(element.type);
	},
	getLength: function(value, element) {
		switch( element.nodeName.toLowerCase() ) {
		case 'select':
			return $("option:selected", element).length;
		case 'input':
			if( $P.checkable( element) )
				return $('[name='+element.name+']').filter(':checked').length;
		}
		return value.length;
	},
	v: function(config,me){
		var msg = '';
		var bfirst = true;
		var ret = true ;
		var value = '';
		var caption = '';
		var tab ,row,col;
		
		switch( me.nodeName.toLowerCase()){
			case 'input':
				if( $P.checkable( me) )
					value = $('[name='+me.name+']').filter(':checked').val();
				else
					value = $(me).val();
				break;
			default:
				value = $(me).val();
			break;
		}
		
		if(config['required'] != undefined){
			var data = config['required'];
			if(eval(data) == true){
				switch( me.nodeName.toLowerCase() ) {
					case 'select':
						// could be an array for select-multiple or a string, both are fine this way
						var val = $(me).val();
						ret = val && val.length > 0;
						break;
					case 'input':
						if ( $P.checkable(me) )
							ret = this.getLength(value, me) > 0;
						break;
					default:
						ret = $.trim(value).length > 0;
				}
				if(!ret){
					msg = $.validator.messages['required'];
					bfirst = false;
				}
			}
		}
		
		if(config['required'] == undefined || config['required']==false){
			if(value.trim() == ''){
				$P.grid.status = 1;
				$P.reseterror();
				$(me).trigger('vsucc',me);
				eval($(me).gv('vsucc'));
				return true;
			}
		}
		
		if(ret){				
			if(config['number'] != undefined){
				var data = config['number'];
				if(data['value'] == undefined)
					data['value'] = value;
				
				var dot = data['dot'];
				if($P.number(data) != true){
					if(!bfirst){
						msg += '<br>';
					}
					if(dot != undefined){
						if(dot == 0){
							msg += '請輸入整數';
						}else if(dot > 0){
							msg += $.validator.format('請輸入{0}位小數',dot);
						}else{
							msg += '請輸入數字';
						}
					}
					
					if(data['min'] != undefined && data['max'] != undefined){
						msg += $.validator.format(',值域[{0}-{1}]',data['min'],data['max']);
					}else{
						if(data['min'] != undefined){
							msg += $.validator.format(',最小值[{0}]',data['min']);
						}
						
						if(data['max'] != undefined){
							msg += $.validator.format(',最大值[{0}]',data['max']);
						}
					}
				}
				data=null;
			}else if(config['custom'] != undefined){
				var data = config['custom'];
				var rs ;
				if((typeof data['fun']) == 'function'){
					rs = data['fun'].call(this,data['args']);
				}else if((typeof data['code']) == 'string'){
					rs = eval(data['code']);
				}
				
				if(rs){
					if(!((rs.ret+'') == '1' || (rs.ret+'') == 'true')){
						msg += $P.gv(rs['msg']);
					}
				}
				data=null;
			}else if(config['spchar'] != undefined){//檢查特殊字符
				var data = config['spchar'];
				var ay = ["'","、"];
				for(var i=0;i<ay.length;i++){
					if(eval("/"+ay[i]+"{1}/").exec(value) != null){
						msg +=$.validator.format('內容中不能包含特殊字符[{0}]!',ay[i]);
						if(data['default'] == true){
							$(me).val(value.replace(new RegExp(""+ay[i]+"{1}", "g"), ""));
						}
						break;
					}
				}
				ay = null;
				data=null;
			}
		}
		
		if(msg != ''){
			caption = $(me).gv('caption');
			if(config['type'] == 'other'){
				if(caption != '' && caption != undefined){
					msg = $.validator.format('{0}',caption)+msg; 
				}
			}else{
				$P.grid.status = 0;
				tab = $(me).parents('.listing');
				row = $(me).gv('index','') != '' ? $(me).gv('index','') :($I(me)+1);
				
				if(caption == ''){
					td = $(me).parents('td');
					col = $I(td,$(tab.find('tbody tr')[row-1]).find('td'));
					caption = $P.gv($(tab.find('thead tr th')[col]).text());
				}
				
				if(caption != '' && caption != undefined){
					var str =  $.validator.format('{0}',caption);
					str += $.validator.format('(第[{0}]行) ',row);
					msg = str+msg; 
				}
			}
			
			$P.processresult({ret:0,info:msg});
			$(me).addClass("errorFiled");
			try{
				$(me).select1();
				$(me).trigger('onfail',[me]);
				eval($(me).gv('vfail'));
			}catch(e){alert(e);}
			return false;
		}else{
			if(config['type'] == 'other'){
				
			}else{
				$P.grid.status = 1;
			}
			$P.reseterror();
			$(me).trigger('onsucc',[me]);
			eval($(me).gv('vsucc'));
			return true;
		}
	},
	diffDate:function (day1, day2){
        var date1 = new Date(day1);
        var date2 = new Date(day2);
        var result = (date2.getTime() - date1.getTime()) / (1000 * 3600 * 24); // A day in milliseconds
        return result;
    },
	adddate:function(dtDate,NumDay,type,format){
		var date ;
		if((typeof dtDate) == 'object' || (typeof dtDate) == 'date'){
			date = dtDate;
		}else{
			date = new Date(dtDate);
		}
		
     	var lIntval = parseInt(NumDay);//间隔 
     	
     	var _type = 4; //类型  
     	if((typeof type) == 'number'){
     		_type = type;
     	}
     	
     	var _format = 'yyyy/MM/dd';
     	if((typeof format) == 'String'){
     		_format = format;
     	}
     	
		switch(_type){ 
			case 7 ://年 
	        	date.setYear(date.getFullYear() + lIntval);break; 
	       	case 6 ://季度 
	        	date.setMonth(date.getMonth() + (lIntval * 3) );break; 
	       	case 5 ://月 
	         	date.setMonth(date.getMonth() + lIntval);break; 
	       	case 4 ://天 
	         	date.setDate(date.getDate() + lIntval); break;
	       	case 3 ://时 
	         	date.setHours(date.getHours() + lIntval);break;
	       	case 2 ://分 
	         	date.setMinutes(date.getMinutes() + lIntval);break;
	       	case 1 ://秒 
	         	date.setSeconds(date.getSeconds() + lIntval);break;  
	     }
	     return $.format.date(date,_format);  
   },
   jsonToString: function(obj,split){  
		var THIS = this;
		if(split == undefined) split = '\"';
	    switch(typeof(obj)){  
	    	case 'string':  
	        	return split + obj.replace(/(["\\])/g, '\\$1') + split;  
	        case 'array':  
	            return '[' + obj.map(THIS.jsonToString).join(',') + ']';  
	        case 'object':  
	        	if(obj instanceof Array){  
	            	var strArr = [];  
	                var len = obj.length;  
	                for(var i=0; i<len; i++){  
	                    strArr.push(THIS.jsonToString(obj[i],split));  
	                }  
	                return '[' + strArr.join(',') + ']';  
	             }else if(obj==null){  
	                return 'null';  
	  
	             }else{  
	             	var string = [];  
	                for (var property in obj) string.push(THIS.jsonToString(property,split) + ':' + THIS.jsonToString(obj[property],split));  
	                return '{' + string.join(',') + '}';  
	             }  
			case 'number':  
			    return obj;  
			case false:  
			    return obj;  
		}
	},
	jsonToUrl:function(json){
		var str = '';
		for(var key in json){
			str += '&';
			str += $P.encode(key)+'=';
			str += $P.encode($P.gv(json[key]));
		}
		return str ;
	},
	editorControl: function(tempConfig){
		var config ;
		if(tempConfig.target){
			config = tempConfig.data;
		}else{
			config = tempConfig;
		}
		
		var me = config['me'];
		if(me == undefined) {
			me = this;
			config['me'] = me;
		}
		if($(me).data('editing') == true)return ;
		$(me).data('editing',true);
		
		$P.getEditor(config);
	},
	getEditor: function(config){
		//bedit
		var me = config['me'];
		var colconfig = config['colconfig'];
		var name = config['name'];
		var index = config['index'];
		//if($(this).find('input[name='+name+']').length > 0)return;//如果還在編輯狀態,則返回
		var field ;
		if($(me).find('#field').length > 0){
			field = $(me).find('#field');
		}else{
			field = me;
		}
		
		var value = "";
		//初始化編輯器
		var editor = null;
		var container = null;
		
		if($P.grid.editors[colconfig['editorid']]){
			editor = $P.grid.editors[colconfig['editorid']];
			container = editor;
			if(colconfig['editor'] == 'combobox'){
				editor = container.find('input[type=text]');
				editor.removeData('record');
				if(editor.data('bblur') == 'false'){
					editor.trigger('blur');
				}else{
					editor.data('bblur','false');
				}
			}else if(colconfig['editor'] == 'multiselect'){
				editor = container.find('input[type=text]');
				if(editor.data('bblur') == 'false'){
					editor.trigger('blur');
				}else{
					editor.data('bblur','false');
				}
			}
			
			if(!editor.data('blur_event')){
				if(colconfig['removevent'] == undefined || colconfig['removevent'] == true){
					editor.unbind('blur');
					editor.unbind('change');
				}
				editor.bind('blur',{td:me,colconfig:colconfig,index:index},$P.editorEnd);
				if(colconfig['editor'] == 'calendar' || colconfig['editor'] == 'combobox' || colconfig['editor'] == 'multiselect'){
					editor.bind('onpicked',function(event){$(this).parents('td:first').addClass('grid-dirty');$(this).parents('tr:first').attr('dirty',true);});
				}else if(colconfig['editor'] == 'org'){
					editor.bind('picked',function(event){$(this).parents('td:first').addClass('grid-dirty');$(this).parents('tr:first').attr('dirty',true);});
				}else{
					editor.bind('change',function(event){$(this).parents('td:first').addClass('grid-dirty');$(this).parents('tr:first').attr('dirty',true);});
				}
			}else{	
				editor.data('blur_event',true);
			}
		}else if(colconfig['editor'] == 'text'){
			value = $P.gv($(field).text());
			editor = '<input autocomplete="off" type="text" name="'+name+'" ';
			editor += ' value="'+value+'"';
			editor += ' oldvalue="'+value+'"';
			editor += ' />';
			editor = $(editor);
			container = editor;
			editor.unbind('blur');
			editor.unbind('change');
			editor.bind('blur',{td:me,colconfig:colconfig,index:index},$P.editorEnd);
			editor.bind('change',function(event){$(this).parents('td:first').addClass('grid-dirty');$(this).parents('td:first').attr('dirty',true);});
		}		
		editor.focus1();
		
		editor.removeClass('editFiled');
		
		//設定編輯器的值
		if(colconfig['editor'] == 'text' || colconfig['editor'] == 'textarea' || colconfig['editor'] == 'calendar'){
			value = $P.gv($(field).text());
			editor.val(value);
			editor.attr('oldvalue',value);
		}else if(colconfig['editor'] == 'select'){
			value = $P.gv($(field).gv('value'));
			editor.val(value);
			editor.attr('oldvalue',value);
		}else if(colconfig['editor'] == 'org'){
			value = $P.gv($(field).gv('value'));
			$('input[name='+editor.gv('hdname')+']').val(value);
			editor.val($P.gv($(field).text()));
			editor.attr('oldvalue',$P.gv($(field).text()));
		}else if(colconfig['editor'] == 'combobox' || colconfig['editor'] == 'multiselect'){
			if(editor.gv('single') == 'true'){
				value = $P.gv($(field).text());
				editor.val(value);
				editor.attr('oldvalue',value);
			}else{
				value = $P.gv($(field).gv('value'));
				$('input[id='+editor.gv('hiddenid')+']').val(value);
				editor.val($P.gv($(field).text()));
				editor.attr('oldvalue',$P.gv($(field).text()));
			}
		}
		
		//設定編輯器的樣式
		if(colconfig['width'] != 'custom' && !(colconfig['editor'] == 'combobox' || colconfig['editor'] == 'multiselect')){
			if(colconfig['width'] != undefined){
				editor.width(colconfig['width']);
			}else{
				editor.width($(me).width()-4);
			}
		}
//		editor.height(10);
		//text.css('border','0px');
		if(!$P.isne($P.grid.keydownconfig[config.tabid]) && (!editor.data('event_keydow')
				|| (!$P.isne(editor.data('tabid')) && editor.data('tabid') != config.tabid)
				)){
			editor.keydown($P.grid.keydown);
			editor.data('event_keydow',true);
			editor.data('tabid',config.tabid);
		}	
		
		var bvalid = true;
		if(eval('typeof '+colconfig['bedit']) == 'function'){
			bvalid = eval(colconfig['bedit']).call(me,{value:value,index:index,record:$('#record'+index).getRecord(),editor:editor,colconfig:colconfig}) ;
		}
		
		if(bvalid){
			$(field).text('');
			$(field).append(container);
			editor.select1();
		}else{
			$(me).data('editing',false);
		}
		
		editor = null;
		container = null;
		delete index;delete value;delete config;delete tempConfig;delete colconfig;delete td;delete field;
	},
	editorEnd: function(tempConfig){
		var me ;
		//aedit
		var config ;
		if(tempConfig.target){
			me = tempConfig.target;
			if(me == undefined){
				me = tempConfig.srcElement;
			}
			config = tempConfig.data;
		}else{
			config = tempConfig;
			me = this;
		}
		
		
		var colconfig = config['colconfig'];
		if(colconfig['editor'] == 'calendar'){
			if($dp.dd.style.display != 'none' && $dp.dd.style.top != "-970px"){
				return false;
			}
		}else if(colconfig['editor'] == 'combobox'){
			if(tempConfig.originalEvent){
				var originalel = null;
				if($P.bie){
					originalel = $(document.activeElement);
				}else{
					originalel = $(tempConfig.originalEvent.explicitOriginalTarget);
				}
				
				if(originalel[0]== $(me).siblings('img')[0] 
					|| originalel.gv('id') == 'ui-active-menuitem'
					|| originalel.parent().gv('id') == 'ui-active-menuitem'
					|| originalel.gv('id') == colconfig['editorid']+'_dropdown'
					|| originalel[0].nodeName.toLowerCase() == 'body'){
					return false;
				}
			}
			$(me).data('bblur','true');
		}else if(colconfig['editor'] == 'multiselect'){
			if(tempConfig.originalEvent){
				var originalel = null;
				if($P.bie){
					originalel = $(document.activeElement);
				}else{
					originalel = $(tempConfig.originalEvent.explicitOriginalTarget);
				}
				
				if(originalel[0]== $(me).siblings('img')[0] 
					|| originalel.gv('id') == colconfig['editorid']+'_select'
					|| originalel.gv('id') == colconfig['editorid']+'_field'){
					return false;
				}
			}
			$(me).data('bblur','true');
		}else if(colconfig['editor'] == 'org'){
			if($(me).data('isopen') == true){
				return false;
			}
		}
			
		var index = config['index'];
		
		var td = config['td'];
		if(td == undefined) return;
		$(td).data('editing',false);
		
		var field ;
		if($(td).find('#field').length > 0){
			field = $(td).find('#field');
		}else{
			field = td;
		}
		
		var endeditor = $(me).data('endeditor');
		$(me).removeData('endeditor');
		
		$('div[id=columneditors]').append($P.grid.editors[colconfig['editorid']]);//歸還編輯器
		
		var bvalid = true;
		if(eval('typeof '+colconfig['eedit']) == 'function'){
			bvalid = eval(colconfig['eedit']).call(td,{value:$(me).gv('value'),oldvalue:$(me).gv('oldvalue'),index:index,record:$('#record'+index).getRecord(),editor:me,colconfig:colconfig}) ;
		}
		
		if(bvalid){
			if(colconfig['editor'] == 'select'){
				$(field).attr('value',$(me).val());
				if($(me).val() == ''){
					$(field).text($(me).val());
				}else{
					$(field).text($(me).find('option:selected').text());
				}
			}else if(colconfig['editor'] == 'org'){
				$(field).attr('value',$('input[name='+$(me).gv('hdname')+']').val());
				$(field).text($(me).val());
			}else if(colconfig['editor'] == 'combobox'){
				if($(me).gv('single') == 'true'){
					$(field).attr('value',$(me).val());
				}else{
					$(field).attr('value',$('input[id='+$(me).gv('hiddenid')+']').val());
				}
				$(field).text($(me).val());
				
				if ($(me).autocomplete("widget").is(":visible")) {
					$(me).autocomplete("close");
				}
			}else if(colconfig['editor'] == 'multiselect'){
				if($(me).gv('single') == 'true'){
					$(field).attr('value',$(me).val());
				}else{
					$(field).attr('value',$('input[id='+$(me).gv('hiddenid')+']').val());
				}
				$(field).text($(me).val());
				
				if ($(me).autocomplete("widget").is(":visible")) {
					$(me).autocomplete("close");
				}
			}else{
				$(field).text($(me).val());
			}
		}else{
			if(colconfig['editor'] == 'combobox'){
				if ($(me).autocomplete("widget").is(":visible")) {
					$(me).autocomplete("close");
				}
			}
			
			$('div[id=columneditors]').append($(field)[0].innerHTML);
			$(field).text($(me).gv('oldvalue'));
		}
		
		delete index;delete config;delete td;delete tempConfig;delete colconfig;delete td;delete field;
		if((typeof endeditor) == 'function'){
			endeditor.call();
		}
	},
	isdate:function(strDate,format){
		try{
			if(format == undefined || format == '')
				format = 'yyyy/MM/dd';
			strDate = strDate.trim();
			var oldDate = strDate;
			if(format == 'yyyyMM'){
				strDate = strDate.substring(0,4)+'/'+strDate.substring(4,6)+'/01';
			}
			var date = new Date(strDate);
			
			return oldDate == date.format(format);
		}catch(e){
			return false;
		}
	},
	getfieldhtml:function(_config){
		var config = {captionwidth:'80px'};
		$.extend(config,_config);
		var el = '<td id="{name}_layout">'; 
		el+= '<table width="100%" cellspacing="0px" cellpadding="0px" border="0" class="sp_filed "><colgroup><col width="{captionwidth}"><col width="*"></colgroup><tbody>';
		el+='<tr><th style="" class=""><font class="" name="{name}_caption" id="{name}_caption">{caption} </font></th><td style="">{body}</td></tr>';
		el+='</tbody></table>';
		el+='</td>';
		
		el=$P.format(el,config);
		el = el.replace(new RegExp("(\\{[^\d]*\\})|(\\{body\\})", "g"), '');
		return el;
	},
	format: function(source, config) {
		$.each(config, function(key, value) {
			source = source.replace(new RegExp("\\{" + key + "\\}", "g"), value);
		});
		return source;
	},
	getoriginalel:function(event){
		var originalel = null;
		if(event.originalEvent){
			if($P.bie){
				originalel = $(event.srcElement);
			}else{
				originalel = $(event.originalEvent.explicitOriginalTarget);
			}
		}
		return originalel ;
	}
}
$P = Utils ;
Utils = null;

$(window).unload(function(){
	var proName = '';
    try {
        for (proName in $P.iframe) {
            try {
                var proValue = $P.iframe[proName];
                if (proValue) {
                    JMRemoveIframe(proValue);
                }
            } catch (e) {
            }
        }
        delete $P.iframe;
    } catch (e) { }
    delete $P;
});

function JMRemoveIframe(if_id) {
    if ($P && $P.iframe) {
        $P.iframe[if_id] = null;
        var obj = document.getElementById(if_id);
        if (obj == null || obj == undefined)
            return;
        obj.src = "javascript:false";
        obj = null;
        delete obj;
    }
}

var AjaxResultHelper ={
	process:function(o)
	{
		if(o.url != null && o.url != '')
			window.location.href = o.url;
		if(o.code != null && o.code != '')
			eval(o.code);
    }
	,
    processbefore: function(o) {
    if (o.bcode!=undefined && o.bcode != null && o.bcode != '')
        eval(o.bcode);
    }
}
var $ARP = AjaxResultHelper.process;
var $ARPB = AjaxResultHelper.processbefore;

function doLoading(tabid,_p){
	var p  = {};
	p['status']= 'loading...';
	p['ret']= 1;
	//p['record']= null;
	
	if(_p != undefined){
		$.extend(p,_p);
	}
	
	var colsconfig = $P.grid.config[tabid];
	if(colsconfig == undefined) return;
	
	var tab = $('#'+tabid);
	var index = $P.gv(tab.data['index'],0);
	
	var tr = $("<tr id='record"+index+"' style=\"height:20px;_height:21px;\"></tr>");
	if(index%2==0){
		tr.addClass('tr-darkstrip');
	}else{
		tr.addClass('tr-lightstrip');
	}
	try{
		if((typeof eval('bloading')) == 'function'){
			p = eval('bloading').call(this,p);
		}
	}catch(e){}
	
	var td , config;
	for(var i=0;i<colsconfig.length;i++){
		config = colsconfig[i];
		var id = config['cid'];
		td = '<td cid="'+id+'" tabid="'+tabid+'">';
		if('status' == id){
			td += '<span style="color:red" id="status'+index+'">'+p['status']+'</span>';
		}else if('toolbar' == id){
			td += '<div id="toolbar'+index+'">&nbsp;</div>';
			//<button type="button" class="btn" onmouseover="$(this).addClass(\'ax-btn-over\');" onmouseout="$(this).removeClass(\'ax-btn-over\');" onmousedown="$(this).addClass(\'ax-btn-pressed\');" onmouseup="$(this).removeClass(\'ax-btn-pressed\');"><div class="btn-inner sx-tb-cancel">取消</div></button>
		}else{
			td += '<div id="field">';
			if(_p == undefined || _p['record'] == undefined){
				td += $P.gv($P.form.gv(id),'&nbsp;');
			}else{
				td += $P.gv($(_p['record']).gv(id),'&nbsp;');
			}
			td += '</div>';
		}
		td +="</td>"
		
		td = $(td);
		if('text' == config['editor']){
			td.attr('edit','true');
			td.bind('click',{name:'e_'+id,index:index,colconfig:config,tabid:tabid},$P.editorControl);
		}
		tr.append(td);
	}
	tab.prepend(tr);
	
	if($('input[name=firstel]').length >0){
		var id = $('input[name=firstel]:checked').val();
		if($P.isne(id)){
			$P.form.setselect(true);
		}else{
			$('#'+id).select1();
		}
	}else{
		$P.form.setselect(true);
	}
	
	if(p['ret'] == 0) return false;
	
	var p = {};
	if(_p == undefined || _p['record'] == undefined){
		p = $P.form.getRecord();
	}else{
		p = _p['record'];
	}
	
	p['action'] = "loading";
	p['index'] = index;
	p['actionvalue'] = "";
	
	var doaction = function(jo){
		 if(jo != undefined && jo.data){
		 	var tempindex = parseInt(jo.data['index']);
		 	$('#status'+tempindex).text($P.gv(jo.data['status'],'&nbsp;'));
		 	var btnhtm = '';
		 	
		 	//加载保存按钮
		 	if($P.gv(jo.data['loadingsaveparams']) != '') {
		 		btnhtm+='&nbsp;';
		 		var saveparams = jo.data['loadingsaveparams'];
		 		saveparams['index']=tempindex;		 		
		 		btnhtm+='<button id="btnsave'+tempindex+'" type="button" onclick="doLoadingSave('+$P.jsonToString(saveparams,"'")+')" class="btn" onmouseover="$(this).addClass(\'ax-btn-over\');" onmouseout="$(this).removeClass(\'ax-btn-over\');" onmousedown="$(this).addClass(\'ax-btn-pressed\');" onmouseup="$(this).removeClass(\'ax-btn-pressed\');"><div class="btn-inner sx-tb-save">修改</div></button>';
		 		delete calparams;
		 	}
		 	
		 	//加载取消按钮
		 	if($P.gv(jo.data['loadingcancelparams']) != '') {
		 		btnhtm+='&nbsp;';
		 		var calparams = jo.data['loadingcancelparams'];
		 		calparams['index']=tempindex;		 		
		 		btnhtm+='<button id="btncancel'+tempindex+'" type="button" onclick="doLoadingCancel('+$P.jsonToString(calparams,"'")+')" class="btn" onmouseover="$(this).addClass(\'ax-btn-over\');" onmouseout="$(this).removeClass(\'ax-btn-over\');" onmousedown="$(this).addClass(\'ax-btn-pressed\');" onmouseup="$(this).removeClass(\'ax-btn-pressed\');"><div class="btn-inner sx-tb-cancel">取消</div></button>';
		 		delete calparams;
		 	}
		 	
		 	//更新记录
		 	if($P.gv(jo.data['loadingrecord']) != '') {
		 		var record = jo.data['loadingrecord'];
		 		$('#record'+tempindex).uptRecord(record);
		 	}
		 	
		 	delete tempindex;
		 	$('#toolbar'+tempindex).html(btnhtm);
		 }	 
	};
	$P.ajax({data : p,succ :doaction,async:true,isValidate:true});
	index++;
	tab.data['index'] = index;
	delete colsconfig;delete tab;delete tr;delete td;delete config;
	return true;
}

function doLoadingCancel(p){
	p['action'] = "loadingCancel";
	$('#status'+p['index']).text('canceling...');
	
	var doaction = function(jo){
		if(jo != undefined && jo.data){
			var tempindex = parseInt(jo.data['index']);
		 	$('#status'+tempindex).text($P.gv(jo.data['status'],'&nbsp;'));
		 	if(jo.ret = 1){
		 		$('#toolbar'+tempindex).empty();
		 	}
		}else{
			$('#status'+index).text('取消失敗!');
		}
	}
	$P.ajax({data : p,succ :doaction,async:true,isValidate:true});
	delete p;
}
 
function doLoadingSave(p){
	var index = p['index'];
	var tr = $('#record'+index);
	if(!tr.isDirty()){  
		alert('無異動資料!');
		return false;
	}
	$.extend(p,tr.getRecord());
	p['action'] = "loadingSave";
	$('#status'+index).text('saving...');
	
	var doaction = function(jo){
		if(jo != undefined && jo.data){
			var tempindex = parseInt(jo.data['index']);
		 	$('#status'+tempindex).text($P.gv(jo.data['status'],'&nbsp;'));
		 	
		 	//更新记录
		 	if($P.gv(jo.data['loadingrecord']) != '') {
		 		var record = jo.data['loadingrecord'];
		 		$('#record'+tempindex).uptRecord(record);
		 	}
		 	
		 	if(jo.ret == 1){
			 	$('#record'+tempindex).commit();
			 }
		}else{
			$('#status'+index).text('保存失敗!');
		}
	}
	$P.ajax({data : p,succ :doaction,async:true,isValidate:true});
	
	delete index;
	delete p;
	delete tr;
}
  
function doPaging(p,page,gridid){
	if((typeof p) != 'number'){
		p = parseInt(p);
	}
	
	if(isNaN(p) || p <= 0 || p > page.totalPage || p == page.currentPage){
		return false;
	}
	try{
		$('input[name='+gridid+'_page]').val(p);
		var action = $('#oldaction').val();
		var actionvalue = $('#oldactionvalue').val();
		
		if(action == ''){
			if($P.loading != null)
				$P.loading.show();
			
			$P.form.getForm().target="_self";
			submitForm();
			return false;
		}
		
		if(action != 'search')
			return false;
		doAction({action:action,actionvalue:actionvalue});
	}catch(e){
		
	}
	return false;
}

function submitForm(p){
	if($P.form.getForm().target=="_self")
		$P.form.status = 1 ;
		
	var key = $('input[type=hidden][name=action]').val()+'-'+$('input[type=hidden][name=actionvalue]').val();
	var cf = $P.confirm[key];
	
	if(cf != undefined && cf != ''){
		if(!confirm($.validator.format($P.msg['confirm'],cf))){
			if($P.loading != null)
				$P.loading.hide();
			return false;
		}	
	}
	
	for(var id in $P.form.enabitems){
		var els = $('input[id='+id+'],textarea[id='+id+'],select[id='+id+']');
		if(id != null && $P.form.enabitems[id] == true && els.length > 0){
			els[0].disabled=false;
		}
		els = null ;
	}
	$P.form.getForm().submit();
}
//var tt = 0;
//var mg = '';
function doAction(p){
	//tt = new Date().getTime();
	if($P.loading != null && !$P.print){
		$('span[id=loadingtext]').text($(p).gv('actiontext','頁面'));
		$P.loading.show();
	}
	
	//mg += '\r\n loading='+((new Date().getTime() - tt)/1000.0)
	//tt = new Date().getTime();

	$P.form.getForm().target="_self";
	performAction(p);
	
	//mg += '\r\n pa='+((new Date().getTime() - tt)/1000.0)
	//tt = new Date().getTime();
	
	//alert(mg);
	
	//$P.form.reset('action,actionvalue');
	if($P.loading != null && (
		($P.form.getForm().target!="_self") 
		|| $P.form.status == 0)
		){
		$P.loading.hide();
	}
	
}

function performAction(p) {try{
		var action = p['action'];
		var actionvalue = p['actionvalue'];
		$("input[name=action]").val(action);$("input[name=actionvalue]").val(actionvalue);
		var ret = false;
		if(!$P.fast && $P.validator[$P.form.formid] != undefined && action != 'wfcheck'){
			ret = $P.validator[$P.form.formid].form();if(ret) $P.reseterror();
		}else{
			ret = true;
		}
		
		/** you can do sth here ***/
		switch (action) {
			case 'new':
				if(ret) onnew(actionvalue,p);break;
			case 'search':
				if(ret) onsearch(actionvalue,p);break;
			case 'save':
				if(ret) onsave(actionvalue,p);break;
			case 'cancel':
				if(ret) oncancel(actionvalue,p);break;
			case 'delete':
				if(ret) ondelete(actionvalue,p);break;
			case 'copy':
				if(ret) oncopy(actionvalue,p);break;
			case 'start':
				if(ret) onstart(actionvalue,p);break;
			case 'check':
				if(ret) oncheck(actionvalue,p);break;
			case 'export':
				if(ret) onexport(actionvalue,p);break;
			case 'help':
				if(ret) onhelp(actionvalue,p);break;
			case 'print':
				if(ret) onprint(actionvalue,p);break;
			case 'printpreview':
				if(ret) onprintpreview(actionvalue,p);break;
			case 'printstep':
				if(ret) onprintstep(actionvalue,p);break;
			case 'wfcheck':
				if(ret) onwfcheck(actionvalue,p);break;
			case 'wfstart':
				if(ret) onwfstart(actionvalue,p);break;
			case 'wfcancel':
				if(ret) onwfcancel(actionvalue,p);break;
			default:
				if(ret) oncustomaction(p);break;;
		}
		/**************************/
}catch(e){alert(e.message);}return false;}

function onnew(actionvalue,p){
	submitForm(p);
}

function onsearch(actionvalue,p){
	submitForm(p);
}

function onsave(actionvalue,p){
	submitForm(p);
}

function oncancel(actionvalue,p){
	submitForm(p);
}

function ondelete(actionvalue,p){
	submitForm(p);
}

function oncopy(actionvalue,p){
	submitForm(p);
}

function onstart(actionvalue,p){
	submitForm(p);
}

function oncheck(actionvalue,p){
	submitForm(p);
}

function onprint(actionvalue,p){
	if($P.print)
		window.print();
	return;
}

function onwfcheck(actionvalue,p){
	submitForm(p);
}

function onwfstart(actionvalue,p){
	submitForm(p);
}

function onwfcancel(actionvalue,p){
	submitForm(p);
}

function onprintpreview(actionvalue,p){
	try{
		document.all.WebBrowser.ExecWB(7,1);
	}catch(e){
	
	}
	return;
}

function onprintstep(actionvalue,p){
	try{
		document.all.WebBrowser.ExecWB(8,1)
	}catch(e){
		
	}
	return;
}

function onexport (actionvalue,p){//export action
	if($P.onexportvalidate(actionvalue)){
		//var exportwind = $P.openwin('about:blank','exportwind','','',200,100);
		//$(exportwind).focusout(function(){alert('sss');this.close();});
		$P.form.getForm().target="_bank";
		var strAction = $($P.form.getForm()).attr('action');
		if(strAction.indexOf('jsessionid') < 0){
			$($P.form.getForm()).attr('action',strAction+';jsessionid='+$P.jsessionid);
		}
		submitForm(p);
	}
}

function onhelp (actionvalue,p){//help action
	if($P.helpurl == '')
		$P.helpurl = 'about:blank';
	$P.openwin($P.helpurl,'helpwindow')
	return false;
}

function oncustomaction(p){
	submitForm(p);
}

var readonly_blur = function(){try{this.blur();}catch(e){}};
var readonly_setCapture = function(){try{this.setCapture();}catch(e){}};
var readonly_releaseCapture = function(){try{this.releaseCapture();}catch(e){}};
$.fn.readonly=function(benab){
	try{
		if(benab == undefined || benab == false){
			$(this).attr('disabled',true);
//			$(this).mouseover(readonly_setCapture);
//			$(this).mouseout(readonly_releaseCapture);
//			$(this).click(readonly_blur);
//			$(this).focus(readonly_blur);
		}else{
//			$(this).unbind('click',readonly_blur);
//			$(this).unbind('focus',readonly_blur);
//			$(this).unbind('mouseover',readonly_setCapture);
//			$(this).unbind('mouseout',readonly_releaseCapture);
			if($P.isie()){
	    			el[0].disabled = false;
	    		}else{
		    		$(this).removeAttr('disabled');
	    		}
		}
	}catch(e){alert(e);}
}

$.fn.isactive=function(bignoreReadonly){
	if('false' == $(this).attr('enab'))
		return false;
		
	if('hidden' == $(this).attr('type'))
		return false;
	
	if(bignoreReadonly != true){
		if('readonly' == $(this).attr('readonly') || 'true' == $(this).attr('readonly'))
			return false;
	}
	
	if('disabled' == $(this).attr('disabled') || 'true' == $(this).attr('disabled'))
		return false;
	return true;
}

$.fn.gv=function(key,def){
	var _def ;
	if($P.isnullorempty(def)){
		_def = '';
	}else{
		_def = def ;
	}
	if(key == 'text' && 'option'==$(this)[0].nodeName.toLowerCase()){
		return $P.gv($(this).text(),_def);
	}else{
		return $P.gv($(this).attr(key),_def);
	}
}

$.fn.isDirty=function(){
	if(this.gv('class').indexOf('grid-dirty') > 0){
		return true;
	}else{
		return this.find('.grid-dirty').length > 0;
	}
}

$.fn.commit=function(){
	this.removeClass('grid-dirty');
	this.find('.grid-dirty').removeClass('grid-dirty');
}

$.fn.intRecord=function(data,_cg){
	var cg = {};
	$.extend(cg,_cg);
	
	if(this[0] && 'table'==this[0].nodeName.toLowerCase()){
		if(cg && cg['reset'] == true){
			$(this).data['index']= 0 ;
			$(this).find('tbody').empty();
		}
		
		if(data == undefined || data.length == undefined || data.length == 0) return ;
		
		var colsconfig = $P.grid.config[$(this).gv('id')];
		if(colsconfig == undefined) return;
		
		var tab = this;
		var tabid = $(this).gv('id');
		var index = $P.gv(tab.data['index'],0);
		var cols = {};
		var td , config,record;
		var  mergetd = {};
		
		for(var i=0;i<data.length;i++){
			record = data[i];
			$.extend(cols,record);
			record = cols;
			
			var tr = $("<tr id='record"+index+"' style=\"height:20px;_height:21px;\"></tr>");
			if(index%2==0){
				tr.addClass('tr-darkstrip');
			}else{
				tr.addClass('tr-lightstrip');
			}
			
			for(var j=0;j<colsconfig.length;j++){
				config = colsconfig[j];
				var id = config['cid'];
				var text = $P.gv(record[id],'&nbsp;');
				
				var bmerge = false;
				if(cg['merge'] == 'auto'){
					var lasttd = mergetd[id];
					var keyvalue = "";
					var keys = $P.gv(config['keys']) == '' ? [] : $P.gv(config['keys']).split(',');
					
					if(keys && keys.length > 0){
						for(var k in keys){
							if(k > 0) keyvalue += '#';
							keyvalue += $P.gv(record[keys[k]],'&nbsp;');
						}
					}else{
						keyvalue = text ;
					}
					
					if(config['merge'] == true && lasttd != undefined && lasttd['keyvalue'] ==keyvalue){
						lasttd['rowspan'] = parseInt($P.gv(lasttd['rowspan'],'0')+1);
						$(lasttd['td']).attr('rowspan',lasttd['rowspan']);
						mergetd[id] = lasttd;
						bmerge = true;
					}
				}
				
				if(cg['merge'] == undefined || !bmerge){
					td = '<td cid="'+id+'" tabid="'+tabid+'">';
					if('status' == id){
						td += '<span style="color:red" id="status'+index+'">'+$P.gv(record[id],'loading...')+'</span>';
					}else if('toolbar' == id){
						td += '<div id="toolbar'+index+'">&nbsp;</div>';
						//<button type="button" class="btn" onmouseover="$(this).addClass(\'ax-btn-over\');" onmouseout="$(this).removeClass(\'ax-btn-over\');" onmousedown="$(this).addClass(\'ax-btn-pressed\');" onmouseup="$(this).removeClass(\'ax-btn-pressed\');"><div class="btn-inner sx-tb-cancel">取消</div></button>
					}else{
						td += '<div id="field">';
						td += $P.gv(record[id],'&nbsp;');
						td += '</div>';
					}
					td +="</td>"
					
					td = $(td);
					if(config['editor'] != undefined){
						td.attr('edit','true');
						td.bind('click',{name:'e_'+id,index:index,colconfig:config,tabid:tabid},$P.editorControl);
					}
					tr.append(td);
					
					if(cg['merge'] == 'auto' && config['merge'] == true){
						var tempLasttd = {};
						tempLasttd['td'] = td;
						tempLasttd['keyvalue'] = keyvalue;
						tempLasttd['rowspan'] = parseInt($P.gv(tempLasttd['rowspan'],'0'))+1;
						mergetd[id] = tempLasttd;
						delete tempLasttd;
					}
					delete text;
				}
			}
			
			if(cg['postion'] == 'pre'){
				tab.find('tbody').prepend(tr);
			}else{
				tab.find('tbody').append(tr);
			}
			
			index++;
			tab.data['index'] = index;
			delete td;delete tr;
		}
		delete colsconfig;delete tab;delete config;delete cg;delete _cg;delete mergetd;delete cols;
	}
}

$.fn.uptRecord=function(record){
	if(this[0] && 'tr'==this[0].nodeName.toLowerCase()){
		var tr = this;
		for (var key in record){
			var els = this.find('[id='+key+']');
			if(els.length == 0){
				els = this.find('[name='+key+']');
			}
			
			this.find('[cid='+key+']').each(function(){
				var el = $(this).find('#field');
				if(el.length >0){
					el.html($P.gv(record[key]));
				}else if(els.length == 0){
					$(this).html($P.gv(record[key]));
				}
				delete el;
			});
			
			var bradioOrcheckbox = false;
			els.each(function(){
				switch( this.nodeName.toLowerCase() ) {
					case 'select':
						$(this).val($P.gv(record[key]));
						break;
					case 'input':
						if($(this).gv('type') == 'text' || $(this).gv('type') == 'textarea' || $(this).gv('type') == 'hidden'){
							$(this).val($P.gv(record[key]));
						}else{
							bradioOrcheckbox = true;
						}
						break;
					default:
						$(this).html($P.gv(record[key]));
				}
			});
			if(bradioOrcheckbox){
				els = tr.find('[id='+key+'][value='+$P.gv(record[key])+']');
				if(els.length == 0)
					els = tr.find('[name='+key+'][value='+$P.gv(record[key])+']');
				els.attr('checked',true);
			}
			delete els;
		}
		delete tr;
	}
}

$.fn.getRecords = function(){
	var ay = new Array();
	this.each(function (){
		ay.push($(this).getRecord());	
	});
	return ay;
}

$.fn.getRecord=function(){
	var record = {};
	if(this[0] && 'tr'==this[0].nodeName.toLowerCase()){
		this.find('> td').each(function(){
			var cid = $(this).gv('cid');
			var td = this;
			if( cid!= ''){
				var field ;
				if($(this).find('#field').length > 0){
					field = $(this).find('#field');
				}else{
					field = this;
				}
				
				if($(this).gv('editor') == 'select' || $(this).gv('editor') == 'org' || $(this).gv('editor') == 'combobox'){
					record[cid]=$(field).gv('value');
					record[cid+'_text']=$(field).text().trim();
				}else{
					record[cid]=$(field).text().trim();
				}
			}
			
			$(this).find('input[type=text]').each(function(){record[$(this).gv('name')]=$(this).val();});
			$(this).find('input[type=hidden]').each(function(){record[$(this).gv('name')]=$(this).val();});
			$(this).find('input[type=select]').each(function(){record[$(this).gv('name')]=$(this).val();});
			$(this).find('textarea').each(function(){record[$(this).gv('name')]=$(this).val();});
			var tempname = "";
			$(this).find('input[type=checkbox]').each(function(){
				var name = $(this).gv('name');
				if(tempname == '' || (","+tempname).indexOf(','+name+',') < 0){
					tempname += name+',';
					var el = $(td).find('input[type=checkbox][name='+name+']:checked');
					if(el.length == 1){
						record[name]=$P.gv(el.val());
					}else if(el.length > 0){
						var ay = [];
						el.each(function(){ay.push($P.gv($(this).val()));});
						record[name]=ay;
					}else{
						record[name]='';
					}
					delete name ;
					delete el;
				}
			});
			tempname='';
			$(this).find('input[type=radiao]').each(function(){
				var name = $(this).gv('name');
				if(tempname == '' || (","+tempname).indexOf(','+name+',') < 0){
					tempname += name+',';
					var el = $(td).find('input[type=checkbox][name='+name+']:checked');
					if(el.length == 1){
						record[name]=$P.gv(el.val());
					}else{
						record[name]='';
					}
					delete name ;
					delete el;
				}
			});
			delete tempname;
			delete td;
			delete cid;
		});
	}
	return record;
}

$.fn.jmContextMenu=function(config){
	if(config['menuid'] == undefined) return false;
	var menu1 = $P.getcontextmenu(config['menuid']);
	$.extend(menu1.config,config);
	$(this).bind('contextmenu',function(event){
		menu1.xtype = 'contextmenu';
		menu1.show(this,event);
		return false;
	});
}

$.fn.drag=function(_config){
	var config = {
			cursor: "move",
			cursorAt: { top: 0, left: 0 },
			helper: function( event ) { 
				return $("<div class=\"x-helper\" style=\"width:120px;\">有一些數據被拖動!</div>");
			}
	};
	if(_config != undefined)
		$.extend(config,_config);
	return $(this).draggable(config);
}

$.fn.drop=function(_config){
	var config = {
			tolerance:'touch',
			over:function(event, ui){
				ui['helper'].addClass('x-helper-hover');
			},
			out:function(event, ui){
				ui['helper'].removeClass('x-helper-hover');
			},accept:function(event, ui){
				return true;
			}
	};
	if(_config != undefined)
		$.extend(config,_config);
	$.extend(config,_config);
	return $(this).droppable(config);
}

$.fn.select1=function(){
	var me = this ;
	setTimeout(function(){$(me).select();delete me;},1);
}

$.fn.focus1=function(){
	var me = this ;
	setTimeout(function(){$(me).focus();delete me;},1);
}

$.fn.attr1=function(_1,_2){
	this.attr(_1,_2);
	this.each(function(){
		if($(this).gv('oncheck') != '')
			eval($(this).gv('oncheck'));
	});
}

function $I(me,bid,nodeName){
	if(bid == true){
		return $('[id='+$(me).attr('id')+']').index($(me));
	}else if((typeof bid) == 'object'){
		return $(bid).index($(me));
	}else if($(me).gv('cid') != '' && $(me).gv('edit') == 'true'){
		if($(me).gv('tabid') != ''){
			return $('table[id='+$(me).gv('tabid')+'] td[cid='+$(me).gv('cid')+']').index($(me));
		}else{
			return $('td[cid='+$(me).gv('cid')+']').index($(me));
		}
	}else{
		if(nodeName == undefined || nodeName== ''){
			nodeName = $(me)[0].nodeName;
		}
		return $(nodeName+'[name='+$(me).attr('name')+']').index($(me));
	}
}

String.prototype.trim=function(){
	return $.trim(this);
}
Date.prototype.format = function(format){
	if(format == undefined || format == '')
		format = 'yyyy/MM/dd';
	var o = {
		"M+" : this.getMonth()+1, //month
		"d+" : this.getDate(),    //day
		"h+" : this.getHours(),   //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3),  //quarter
		"S" : this.getMilliseconds() //millisecond
	}
	
	if(/(y+)/.test(format)){ 
		format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	
	for(var k in o){
		if(new RegExp("("+ k +")").test(format))
			format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] :("00"+ o[k]).substr((""+ o[k]).length));
	}
  return format;
} 
function doMenu(p){
	
}